Jquery if else语句没有改变变量

时间:2018-05-03 16:46:09

标签: javascript jquery

我确定这是愚蠢的,但我无法找到为什么点击变量没有变为真 点击箭头后。我在这里使用jQuery。

var clicked = false;
if (!clicked){
    $('#click').on('click', function(){
        alert('clicked');
        clicked = true;
    });
}else {
    $('#click').on('click', function(){
        alert('clicked again');
    });
}

直播示例(也作为fiddle):



var clicked = false;
if (!clicked){
    $('#click').on('click', function(){
        alert('clicked');
        clicked = true;
    // end
    });
}else {
    $('#click').on('click', function(){
        alert('clicked again');
    });
}

<div class="col-lg-1 team_padding">
<p id="click">click me</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

确实如此,但这并没有改变你所连接的事件处理程序。下一次点击只会再次运行相同的处理程序(if块中的那个),因为您显示的代码只运行一次,设置一< / strong>处理程序。证明:

&#13;
&#13;
var clicked = false;
if (!clicked){
    $('#click').on('click', function(){
        alert('clicked');
        clicked = true;
    });
}else {
    $('#click').on('click', function(){
        alert('clicked again');
    });
}
var timer = setInterval(function() {
  console.log("clicked = ", clicked);
}, 1000);
setTimeout(function() {
  clearInterval(timer);
}, 10000);
&#13;
<div class="col-lg-1 team_padding">
<p id="click">click me</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

相反,将条件逻辑移动到处理程序中:

var clicked = false;
$('#click').on('click', function(){
    if (!clicked) {
        alert('clicked');
        clicked = true;
    } else {
        alert('clicked again');
    }
});

示例:

&#13;
&#13;
var clicked = false;
$('#click').on('click', function(){
    if (!clicked) {
        alert('clicked');
        clicked = true;
    } else {
        alert('clicked again');
    }
});
&#13;
<div class="col-lg-1 team_padding">
<p id="click">click me</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
&#13;
&#13;
&#13;