簡體   English   中英

使用javascript單擊多個div時添加和刪除類

[英]Add and remove classes when click on multiple div using javascript

我實際上試圖在單擊時將類(選定)添加到標簽並從鄰居標簽中刪除類。

問題是當有 2 個 div 時它不起作用,下面的代碼僅適用於第一個 Div 或當我單擊第二個標簽的標簽時,第一個活動標簽被刪除

 const menuLis = document.querySelectorAll(".top-nav > label"); for (let label of menuLis) { label.addEventListener("click", function(){ // 1. Remove Class from All Lis for (let label of menuLis) { label.classList.remove('selected'); } // 2. Add Class to Relevant Li this.classList.add('selected'); }); }
 .selected{color:red}
 <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div> <br><br> <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div>

謝謝

您正在從menuLis所有項目中menuLis 您應該獲得當前.top-nav部分中僅包含標簽的列表,並從中刪除類。

 const menuLis = document.querySelectorAll(".top-nav > label"); for (let label of menuLis) { label.addEventListener("click", function(){ let container = this.closest('.top-nav'); let curMenuLis = container.querySelectorAll("label"); // 1. Remove Class from All Lis for (let label of curMenuLis) { label.classList.remove('selected'); } // 2. Add Class to Relevant Li this.classList.add('selected'); }); }
 .selected{color:red}
 <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div> <br><br> <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM