使用同一个按钮循环触发三个事件
Use the same button to trigger three events in a loop
只有一个按钮。
javascript 程序包含 3 个部分。
//section 1
var x = 3;
console.log("x = " + x);
//section 2
x += 7;
console.log("x = " + x);
//section 3:
x += 6;
console.log("x = " + x);
我要实现的效果是:
我正在单击按钮 - 只有第 1 部分正在执行
我再次单击按钮 - 仅执行第 2 部分
我再次单击按钮 - 仅执行第 3 部分
我再次单击按钮 - 仅执行第 1 部分
我再次单击按钮 - 仅执行第 2 部分
等等。
循环不是必需的,这可以使用按钮的相同事件处理程序来完成。
附带说明一下,如果您正在寻找一种逐步调试的方法,可以在右键单击 -> 检查后使用浏览器的 'Debug or Debugger' 选项卡来完成。您可以逐步设置断点和 运行 脚本。
var output = document.getElementById("output");
var theButton = document.getElementById("theButton");
var section = 0;
var x;
theButton.onclick = function(){
section++;
var temporaryResult = "Nothing";
if(section == 4){
section = 1;
}
if(section == 1){
//Do the math
x = 0;
// Set the result to show
temporaryResult = x;
}
if(section == 2){
//Do the math
x += 10;
// Set the result to show
temporaryResult = x;
}
if(section == 3){
x -= 25;
temporaryResult = x;
}
output.innerHTML = temporaryResult;
//For console log:
console.log(temporaryResult);
}
<div id="output">Results here</div>
<button id="theButton">Next</Button>
只有一个按钮。
javascript 程序包含 3 个部分。
//section 1
var x = 3;
console.log("x = " + x);
//section 2
x += 7;
console.log("x = " + x);
//section 3:
x += 6;
console.log("x = " + x);
我要实现的效果是:
我正在单击按钮 - 只有第 1 部分正在执行
我再次单击按钮 - 仅执行第 2 部分
我再次单击按钮 - 仅执行第 3 部分
我再次单击按钮 - 仅执行第 1 部分
我再次单击按钮 - 仅执行第 2 部分
等等。
循环不是必需的,这可以使用按钮的相同事件处理程序来完成。
附带说明一下,如果您正在寻找一种逐步调试的方法,可以在右键单击 -> 检查后使用浏览器的 'Debug or Debugger' 选项卡来完成。您可以逐步设置断点和 运行 脚本。
var output = document.getElementById("output");
var theButton = document.getElementById("theButton");
var section = 0;
var x;
theButton.onclick = function(){
section++;
var temporaryResult = "Nothing";
if(section == 4){
section = 1;
}
if(section == 1){
//Do the math
x = 0;
// Set the result to show
temporaryResult = x;
}
if(section == 2){
//Do the math
x += 10;
// Set the result to show
temporaryResult = x;
}
if(section == 3){
x -= 25;
temporaryResult = x;
}
output.innerHTML = temporaryResult;
//For console log:
console.log(temporaryResult);
}
<div id="output">Results here</div>
<button id="theButton">Next</Button>