繁体   English   中英

为什么我的 if 语句没有响应我对变量所做的更改?

[英]Why doesn't my if statement respond to the changes I made to the variables?

var count = 0;    
if(count % 2 == 0) {
        for (let i = 0; i < squareStorage.length; i++) {
            squareStorage[i].addEventListener("click", function() {
                console.log("This is: " + i)
                console.log(count%2)
                count++;
                console.log(count);
            });
        }
    }
    
else if(count % 2 == 1) {
    console.log(count%2)
        for (let i = 0; i < squareStorage.length; i++) {
            squareStorage[i].addEventListener("click", function() {
            console.log("This is (no.2): " + i)
            count++;
            console.log(count);
        }, false);
    }
}

这些是我的代码的一部分。 我希望在单击放入 squareStorage 变量中的一堆 div 时更改变量计数。 每当我单击时,我都会尝试增加变量计数。 但是,我的 if 语句以某种方式继续运行,即使 count % 2 不是 0。

我认为您忘记了删除可以使用removeEventListener执行的旧事件侦听器。

例如:

function myClickFunction {
 // ... do stuff for first click function
}

// when loading the 2nd click function you run this
squareStorage[i].removeEventListener('click', myClickFunction)

这是一个常见的错误,您需要单独添加事件,然后在事件中调用代码。

这是示例。

 let count = 0; // This method will deal with the logic on each click. // NOTE: we are not re-doing our events. const processClick = () => { if(count%2 == 0) { console.log(`This is one: count ${count}`); } else { console.log(`This is two: count ${count}`); } count++; }; // When document loads we will find all divs and add a click event. document.addEventListener('DOMContentLoaded', () => { // Find all our DIV elements and add a click event to them. document.querySelectorAll('div').forEach(div => div.addEventListener('click', processClick)); });
 <div>Click</div> <div>Click</div> <div>Click</div> <div>Click</div> <div>Click</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM