[英]JQuery Function Running Multiple times for Each Element
我有一个简单的脚本,每秒使用setInterval生成一个div元素。 我面临的问题是addScore()会为窗口中的每个元素触发一次。 因此,如果生成了四个目标,则addScore()函数将运行四次。
<div class="wrap">
<div class="intro">
<p>Simply press go and click the circles as fast as you can!</p>
<button class="go" type="button">Go!</button>
</div>
</div>
<script type="text/javascript">
var score = 0; // Starting score for game
function addScore(){
score++;
console.log(score);
}
function spawnTargets() {
$(".wrap").append("<div class='target'>Hello</div>");
$(".target").click(function(){
$(this).hide();
addScore();
});
}
$(".go").click(function() {
$(".intro").toggle();
setInterval(spawnTargets, 1000);
});
</script>
当您将click事件添加到.target时,您可以使用之前添加的所有div来执行此操作! 请改用:
<script type="text/javascript">
var score = 0; // Starting score for game
function addScore(){
score++;
console.log(score);
}
function spawnTargets() {
$(".wrap").append("<div class='target'>Hello</div>");
}
$(".go").click(function() {
$(".intro").toggle();
setInterval(spawnTargets, 1000);
});
$(".wrap").on('click', '.target', function(){
$(this).hide();
addScore();
});
</script>
.on-function将事件处理程序添加到父元素,并过滤来自.target的click元素。
在对函数进行调用时,您将绑定多个单击事件
function spawnTargets() {
$(".wrap").append("<div class='target'>Hello</div>");
$(".target").click(function(){
$(this).hide();
addScore();
});
}
相反,您需要委派该事件
更改
$(".target").click(function(){
至
$('.wrap').on("click", ".target", function(){
并将其移至函数外部
码
var score = 0; // Starting score for game
function addScore() {
score++;
console.log(score);
}
function spawnTargets() {
$(".wrap").append("<div class='target'>Hello</div>");
}
$('.wrap').on("click", ".target", function () {
$(this).hide();
addScore();
});
$(".go").click(function () {
$(".intro").toggle();
setInterval(spawnTargets, 1000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.