简体   繁体   中英

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:-

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:-

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM