javascript - 运行一次的函数 里面的语句为什么重复执行
本文介绍了javascript - 运行一次的函数 里面的语句为什么重复执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
部分代码如下:
function yourTurn() {
console.log("123");
yourTurnArr = [];
$(".cp").css("cursor", "pointer");
$(".cp").mousedown(function() {
switch (this.id) {
case "red":
$(this).css("background", "#ff4c4c");
break;
case "blue":
$(this).css("background", "#1c8cff");
break;
case "yellow":
$(this).css("background", "#fed93f");
break;
case "green":
$(this).css("background", "#13ff7c");
break;
};
})
$(".cp").mouseup(function() {
switch (this.id) {
case "red":
$(this).css("background", "#9F0F17");
break;
case "blue":
$(this).css("background", "#094A8F");
break;
case "yellow":
$(this).css("background", "#CCA707");
break;
case "green":
$(this).css("background", "#00A74A");
break;
}
yourTurnArr.push(this.id);
})
}
全部代码
查找bug的好方法可以推荐一下也是极好的
解决方案
看了一下楼主的代码。
$("#start-mark").click(function() {
//检查开关是否已经打开
if (state == "off") {
return;
}
// if (count > 1) {
// count = 0;
// }
stateReady();
setTimeout("yourTurn()", (randomColorArr.length + 1) * 1200);
setTimeout("check()", (randomColorArr.length + 1) * 2000);
})
之所以出现多个事件,并不是因为上述代码问题。而是逻辑上有问题。
当#start-mark触发点击事件时会延迟执行yourTurn(),当执行一个yourTurn()就为.cp节点添加mousedown/mouseup事件。如果多次点击。yourTurn()也会执行多次,就会添加多个事件。
要解决这个问题,楼主就要先判断对应节点的状态,如果存在对应的事件,不要再继续添加事件了。
这篇关于javascript - 运行一次的函数 里面的语句为什么重复执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文