[英]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.