2 回答
![?](http://img1.sycdn.imooc.com/545847f50001126402200220-100-100.jpg)
TA贡献1818条经验 获得超8个赞
一种方法是选择.item元素,并创建一个array的.item长度(数.item在页面元素)单独存储用于每一个所述计数器。
这是一个演示,其中包含一些有用的评论:
/** selecting the elements with ".item" class and declaring an array to store each element counter separately **/
const items = document.querySelectorAll('.item'),
countArr = new Array(items.length);
/** loop through the elements and add "mouseup" listener (to ensure catching both left and right clicks) for each element **/
/**
* el: the current element from the ".item" elements collection
* i: the index of that elemnt in the collection
**/
items.forEach((el, i) => {
countArr[i] = 0; /** initialize each array element with 0 so we can count later (new Array puts "undefined" as the array elements values) **/
/** add the "mouseup" listener **/
el.addEventListener('mouseup', e => {
let txtCount = el.querySelector('.count'); /** selecting the "span" that contains the counter from the current elemnt (don't forget that we're looping in ".item" elements collection) **/
if(e.which === 1) countArr[i]++; /** left click **/
else if(e.which === 3) countArr[i]--; /** right click **/
txtCount.textContent = countArr[i]; /** update the "span" wih the calculated counter as left click adds 1 and right click removes 1 from the counter of each element **/
});
});
/** basic styling for the demo **/
.item {
display: inline-block;
margin: 15px 0;
padding: 8px;
border: 2px solid teal;
user-select: none;
}
.item .count {
display: inline-block;
background-color: #181818;
color: #fff;
font-size: 1.2rem;
font-weight: bold;
padding: 8px;
border-radius: 4px;
}
<div class="item">counter = <span class="count">0</span></div>
<div class="item">counter = <span class="count">0</span></div>
<div class="item">counter = <span class="count">0</span></div>
![?](http://img1.sycdn.imooc.com/545861c80001141e02200220-100-100.jpg)
TA贡献1780条经验 获得超1个赞
您需要访问与单击的元素对应的 div。
Usingdocument.querySelector(".item .points")
将始终选择 DOM 中的第一个元素。
您可以使用e.target
访问被单击的元素,并且由于您需要的是该元素的唯一子元素,因此您可以替换
document.querySelector(".item .points").innerHTML = counter;
和
e.target.children[0].innerHTML = counter;
然后你会遇到另一个问题,那就是你的计数器是全局的并且对所有按钮都是通用的。
因此,您将不得不使用哈希图(JS 对象)而不是单个整数 counter
var counter = {};
添加回答
举报