即使条件为假,代码也会被执行

Dom*_*lak 1 jquery

我整个下午都在苦苦挣扎,没有任何帮助我就无法继续前进.

开门见山.

// On document ready
$(function() {
    var stop = false;
    $('#update-cart :input').on('change input', function() {
        // Here you go
        stop = true;
    });

    if (stop === false) {
        // For some(silly) reason It gets executed on input field change 
    }
});
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,if除非输入字段有一些变化,否则上面的代码会继续使用语句,而它会设置新的变量.所以if情况仍然是假的.如果条件为假,我不明白为什么它会被执行.我可能会失踪或做错事.

T.J*_*der 5

只有代码的处理程序运行(并重新运行)在事件发生时.

这是您的代码运行的顺序:

  1. 创建stop变量并将其设置为false.

  2. 连接changeinput处理程序.

  3. 检查if (stop === false),因为这是真的,执行if块中的代码.

  4. 稍后,每当值更改时,设置stoptrue.这对步骤#3中运行的代码没有任何影响.