【问题标题】:Use the same button to trigger three events in a loop使用同一个按钮循环触发三个事件
【发布时间】:2019-03-12 07:13:50
【问题描述】:

只有一个按钮。

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. 我正在点击按钮 - 只有第 1 部分正在执行

  2. 我再次点击按钮 - 仅执行第 2 节

  3. 我再次点击按钮 - 仅执行第 3 节

  4. 我再次单击该按钮 - 仅执行第 1 节

  5. 我再次点击按钮 - 仅执行第 2 节

等等。

【问题讨论】:

    标签: events buttonclick


    【解决方案1】:

    循环不是必需的,这可以使用按钮的相同事件处理程序来完成。

    附带说明,如果您正在寻找一种逐步调试的方法,可以在右键单击后使用浏览器的“调试或调试器”选项卡 -> 检查。您可以设置断点并逐步运行脚本。

    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>

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多