在这段代码中,我试图在猫被选中时显示猫列表中的猫,然后当它们被选中时增加每一只猫的得分 这里的问题是count变量连接在所有猫之间。因此,当我点击任何照片时,计数变量会自动增加。如何为每只猫分配变量计数的不同值?我希望它足够清楚
// displaying the cat when clicked
for (var i = 0; i < catsColumn.length; i++) {
(function () {
var cattt = cats[i];
catsColumn[i].addEventListener('click', function () {
var catDisplay = document.createElement('div');
var catScore = document.innerHTML = "<p id=" + cattt + ">0</p><img class='catDisPic' src='"+ cattt +".jpg'>";
catDisplay.innerHTML = catScore;
catsDisplay.appendChild(catDisplay);
// selecting the cats in the display area and adding event listener
var catPicDis = catsDisplay.getElementsByClassName('catDisPic');
for (var i = 0; i < catPicDis.length; i++) {
(function () {
var count = 0;
catPicDis[i].addEventListener('click', function(){
this.previousSibling.textContent = ++count;
})
}())
}
})
}())
}
答案 0 :(得分:1)
在IIFE中, count 是全局的,所以:
var catPicDis = document.getElementsByClassName('catDisPic');
for (var i = 0; i < catPicDis.length; i++) {
(function() {
// keep count in closure
var count = 0;
catPicDis[i].addEventListener('click', function() {
this.previousSibling.textContent = ++count;
})
}());
}
<div class="catDisPic">catDisPic</div>
<div class="catDisPic">catDisPic</div>
<div class="catDisPic">catDisPic</div>