gpt4 book ai didi

javascript - 如何修复 addEventListener 不起作用?

转载 作者:行者123 更新时间:2023-12-01 00:42:15 27 4
gpt4 key购买 nike

我的代码有两个 addEventListener(),第一个很好,但第二个有问题

let catNames = ['pew', 'haha', 'Tsh', 'bom', 'tok'];
let catPhotos = document.querySelectorAll('li img');
let catNamePlaces = document.querySelectorAll('li p');
let area = document.getElementById('area');
let targetName = document.querySelector('#area p');
let targetImg = document.querySelector('#area img');
let counterArea = document.querySelector('#area div');

for (let i = 0; i < catNames.length; i++) {
catNamePlaces[i].textContent = catNames[i];
}
for (let catPhoto of catPhotos) {
catPhoto.addEventListener('click', function() {
targetImg.src = catPhoto.src;
}, false);
}
let counter = 0;

targetImg.addEventListener('click', (function(num) {
num++;
counterArea.innerHTML = num;
})(counter));
<ul class="container">
<li>
<p></p><img src="cat1.jpg" alt="cat"></li>
<li>
<p></p><img src="cat2.jpg" alt="cat"></li>
<li>
<p></p><img src="cat3.jpg" alt="cat"></li>
<li>
<p></p><img src="cat4.jpg" alt="cat"></li>
<li>
<p></p><img src="cat5.jpg" alt="cat"></li>
</ul>
<div id="area">
<p></p>
<img src="" alt="selectedCat">
<div id="counter"></div>
</div>

我期望第二个 addEventListener 将从 0 开始,然后每次在 targetImg 上单击时都会添加 1,但每次都是从 1 开始,当我点击它时什么也不做。

最佳答案

let catNames = ['pew', 'haha', 'Tsh', 'bom', 'tok'];
let catPhotos = document.querySelectorAll('li img');
let catNamePlaces = document.querySelectorAll('li p');
let area = document.getElementById('area');
let targetName = document.querySelector('#area p');
let targetImg = document.querySelector('#area img');
let counterArea = document.querySelector('#area div');

for (let i = 0; i < catNames.length; i++) {
catNamePlaces[i].textContent = catNames[i];
}
for (let catPhoto of catPhotos) {
catPhoto.addEventListener('click', function() {
targetImg.src = catPhoto.src;
}, false);
}
let counter = 0;
counterArea.innerHTML = counter;

targetImg.addEventListener('click', function(event) {
counter++;
counterArea.innerHTML = counter;
});
<ul class="container">
<li>
<p></p><img src="cat1.jpg" alt="cat"></li>
<li>
<p></p><img src="cat2.jpg" alt="cat"></li>
<li>
<p></p><img src="cat3.jpg" alt="cat"></li>
<li>
<p></p><img src="cat4.jpg" alt="cat"></li>
<li>
<p></p><img src="cat5.jpg" alt="cat"></li>
</ul>
<div id="area">
<p></p>
<img src="" alt="selectedCat">
<div id="counter"></div>
</div>

关于javascript - 如何修复 addEventListener 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57641007/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com