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


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。

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

下面是一个例子。

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>

我想你忘记删除旧的事件监听器了,你可以用removeEventListener

,

function myClickFunction {
// ... do stuff for first click function
}
// when loading the 2nd click function you run this
squareStorage[i].removeEventListener('click', myClickFunction)

最新更新