[英]Javascript addeventlistener hitting click multiple times
The below mentioned code will change icon from watched(-) to unwatched(+) and vice-versa in a list of data(list of icon):-下面提到的代码将在数据列表(图标列表)中将图标从已观看(-)更改为未观看(+),反之亦然:-
ts code:- ts代码:-
const watchListComponent = document.querySelectorAll('.addtoWatchlist');
if (watchListComponent.length) {
watchListComponent.forEach((watchItem) => {
watchItem.addEventListener('click', () => {
console.log('here');
watchItem.querySelector('.icon').classList.toggle('iconWatched');
watchItem.querySelector('.icon').classList.toggle('iconWatchList');
});
});
}
HTML code:- HTML 代码:-
<div class="px-2">
<a href="javascript:void(0)" class="tableInvisibleOption addtoWatchlist tooltipTRWL">
<i class="icon icon20 iconWatchList iconShow" (click)="addToWatchList(fundData)"></i>
<span class="tooltiptextTRWL">Add to Watchlist</span></a>
</div>
In the above case, first time if I click on the unwatched(+) icon it is getting changed to watched(-) for ex:- (+) to (-), and the next time if I click it should change from (-) to (+) but the icon is not changing.在上述情况下,如果我第一次单击未观看(+)图标,它会更改为已观看(-),例如:-(+)到(-),下一次如果我单击它应该从( -) 到 (+) 但图标没有改变。 If I click twice the icon is getting changed from(-) to (+) then if I click twice changing from (+) to (-).
如果我单击两次,图标将从(-)更改为(+),然后如果我单击两次,则从(+)更改为(-)。
Need to change the icon from (+) to (-) and (-) to (+) on single click.需要单击将图标从 (+) 更改为 (-) 和 (-) 更改为 (+)。
Use event delegation .使用事件委托。 A minimal reproducable example for you
为您提供的最小可重现示例
document.addEventListener("click", toggleAddIcon); function toggleAddIcon(evt) { const origin = evt.target; if (origin.classList.contains("icon")) { origin.classList.toggle('iconWatchList'); } }
.icon { cursor: pointer; }.icon.iconWatchList:after { content: ' (on list)'; }
<div class="icon">click</div> <div class="icon">click</div> <div class="icon">click</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.