在这里,我尝试创建一个javascript应用,该应用将对列表中每张照片的每次点击计数,并将此计数添加到出现在“ myimg”中的适当照片中,但是对每次点击进行计数的功能与最后一次计数绑定在一起,添加一个我不想做的 那么如何停止函数绑定?
var nums = ["lolo", "cato", "saloa", "nadya", "kalaf"];
var phos = ["cat1.jpg", "cat2.jpg", "cat3.jpg", "cat4.jpg", "cat5.jpg"];
var x;
var numclicks = [0, 0, 0, 0, 0];
// Let's loop over the numbers in our array
for (var i = 0; i < nums.length; i++) {
// This is the number we're on...
var num = nums[i];
// We're creating a DOM element for the number
var elem = document.createElement('li', 'ul');
elem.textContent = num;
// ... and when we click, alert the value of `num`
elem.addEventListener('click', (function(numCopy) {
return function() {
for (i = 0; i < nums.length; i++) {
if (nums[i] == numCopy) {
x = i
}
}
document.getElementById("catname").innerHTML = numCopy;
document.getElementById("myImg").src = phos[x];
var elemOBJ = document.getElementById("myImg");
elemOBJ.addEventListener('click', (function(xcopy) {
return function() {
document.getElementById("clicks").innerHTML = ++numclicks[xcopy];
alert(numclicks[xcopy]);
return;
}
})(x));
alert("here")
return;
};
})(num));
// finally, let's add this element to the document
document.getElementById("mylist").appendChild(elem);
};
<div id="mylist">listhere</div>
<h1 id="catname"></h1>
<img id="myImg" src="cat1.jpg" width="600" height="400"></img>
<p id="clicks">0</p>