单击按钮更改html文本

you*_*ken 1 html javascript events function button

我几天前进入了js.我开始玩新功能和事件,但我被困在这里

var str = ["A", "b", "c", "d", "e"];

function Generate() {
  var text = document.getElementById("text");
  var countStr = 0;
  text.innerHTML = str[countStr];
  countStr += 1;

}
Run Code Online (Sandbox Code Playgroud)
<div id="quote">
  <p id="text">I'm a paragraph</p>
</div>
<button id="butt" onclick="Generate()">Generate</button>
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,文本变为str [0]但是当我再次单击时它不会改变; 你能告诉我为什么吗 ?

Mih*_*nut 7

这种行为的存在是因为每次click按钮时,countStr变量都将为0.您需要在函数外声明它.

var str = ["A", "b", "c", "d", "e"];
var countStr = 0;
function Generate() {
  var text = document.getElementById("text");  
  text.innerHTML = str[countStr];
  countStr += 1;

}
Run Code Online (Sandbox Code Playgroud)
<div id="quote">
  <p id="text">Im a paragraph</p>
</div>
<button id="butt" onclick="Generate()">Generate</button>
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用一个closure函数.

了解更多有关closures,在这里.

var str = ["A", "b", "c", "d", "e"];
var text = document.getElementById("text");
var generate=(function() {  
  var countStr = 0;
  return function(){
     text.innerHTML = str[countStr];
     return countStr+=1;
  }

})();
Run Code Online (Sandbox Code Playgroud)
<div id="quote">
  <p id="text">I'm a paragraph</p>
</div>
<button id="butt" onclick="generate()">Generate</button>
Run Code Online (Sandbox Code Playgroud)