所以我正在为我的 Udacity 课程中的一个项目创建一个“Cat Clicker”。基本上,我们有 5 张猫的图片(我目前有 4 张),但每张猫图片都应该有自己的点击计数器,用于点击特定图片。我知道有一种方法可以使用一个for
循环,但不确定如何。我一直在尝试只addeventlistener
为每个单独的图像使用一个,但是它会计算页面上的每次点击(无论在哪里)......有人能弄清楚我错过了什么/做错了吗?
var sassy = document.createElement("img");
sassy.src = 'images/cat.jpg';
sassy.height = "500";
sassy.width = "640";
sassy.alt = "Sassy Cat";
document.getElementById("catimage").appendChild(sassy);
var addUp = (function() {
var count = 0;
return function() {
var sassy = document.getElementById("catimage");
if (sassy) sassy.innerHTML = "Picture Clicks: " + ++count;
}
}());
document.addEventListener("click", addUp, false);
var grumpy = document.createElement("img");
grumpy.src = 'images/grumpy-cat.jpg';
grumpy.height = "500";
grumpy.width = "640";
grumpy.alt = "Grumpy Cat";
document.getElementById("grumpyimage").appendChild(grumpy);
var cuddlecats = document.createElement("img");
cuddlecats.src = 'images/cuddles.jpg';
cuddlecats.height = "500";
cuddlecats.width = "640";
cuddlecats.alt = "Cuddling Cats";
document.getElementById("cuddlingcats").appendChild(cuddlecats);
var sketchy = document.createElement("img");
sketchy.src = 'images/sketchycat.jpg';
sketchy.height = "500";
sketchy.width = "640";
sketchy.alt = "Sketchy Cat";
sketchy.co
document.getElementById("sketchycat").appendChild(sketchy);
<div id="catimage">
<figcaption>Sassy Cat</figcaption>
<h3 id="sassycount">Picture Clicks: 0</h3>
</div>
<div id="grumpyimage">
<figcaption>Grumpy Cat</figcaption>
<h3 id="grumpycount">Picture Clicks: 0</h3>
</div>
<div id="cuddlingcats">
<figcaption>Cuddling Cats</figcaption>
<h3 id="cuddlecount">Picture Clicks: 0</h3>
</div>
<div id="sketchycat">
<figcaption>Sketchy Cat</figcaption>
<h3 id="sketchcount">Picture Clicks: 0</h3>
</div>