【问题标题】:Pure JS "If stament depending the number of click"纯JS“if语句取决于点击次数”
【发布时间】:2013-07-22 23:20:37
【问题描述】:

我一直在寻找这个问题,但没有找到解决方案。我正在尝试创建一个代码,当您单击按钮时做一件事,当您稍后按下同一个按钮时做另一件事。我尝试创建和“if-else”语句,但我不能(不知道)如何计算点击次数。

代码是:

<button type="submit" id="btnshwmap" onClick="init()" >Show Map</button>

还有 if-else :

function init() {
    var click =0;
    if (click === 0) {  
        do this  
        var click = 1;  
    } else {  
        do this  
    }
});//end click

基本上我正在尝试使用这个例子Jquery if its the first time element is being clicked

但答案是使用 Jquery 我正在尝试不使用任何库。

非常感谢!

【问题讨论】:

  • click 将在您每次调用init 时重置为0

标签: javascript button if-statement


【解决方案1】:

问题是你每次调用函数时都在重置click=0

我会建议这样的事情:

function init() {
    if( !init.click) {
        // first, third, fifth etc.
        init.click = 1;
    ]
    else {
        // second, fourth...
        init.click = 0;
    }
}

【讨论】:

    【解决方案2】:

    您只需要在函数之外的全局区域中拥有点击计数器。

    var click =0;
    
    function init() {
    
        if (click == 0) {  
            //do this once
            click = 1;  
        } else {  
            //do this every other time
        }
    });//end click
    

    【讨论】:

    • 谢谢!完美运行。谢谢大家的回复!
    【解决方案3】:

    您可以尝试通过单击切换为按钮设置的值。比如:

    function init() {
        var value = document.getElementById('btnshwmap').value;
        if (value === 1) {  
            do this  
            document.getElementById('btnshwmap').value = 2;  
        } else {  
            do this  
            document.getElementById('btnshwmap').value = 1;
        }
    });//end click
    

    或者保留一个全局变量来跟踪点击状态,而不是每次运行函数时都设置。

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多