简体   繁体   English

具有多个元素的 classList.toggle 问题

[英]classList.toggle problem with more than one element

I am currently trying to style a series of buttons so that when clicked they change to a different style and the text content also changes.我目前正在尝试设置一系列按钮的样式,以便在单击时它们会更改为不同的样式并且文本内容也会更改。 It is working except that when I click the another button with the same class, the other button loses its classList toggle.它正在工作,除了当我单击具有相同类的另一个按钮时,另一个按钮失去其 classList 切换。 It all works until I press the button on the next element, and would need them to work independently since they are being used to mark whether the book has been read or not.这一切都有效,直到我按下下一个元素上的按钮,并且需要它们独立工作,因为它们被用来标记这本书是否已被阅读。

 const readButtons = document.querySelectorAll(".book__read-button"); readButtons.forEach((readButton) => { let clickCount = 0; readButton.addEventListener("click", (e) => { readButtons.forEach((f) => f != e.target ? f.classList.remove("clicked") : "" ); e.target.classList.toggle("clicked"); clickCount += 1; if (clickCount % 2 == 0) { readButton.textContent = "Unread"; } else { readButton.textContent = "Read"; } }); });
 .book__read-button.clicked { background-color: green; border: 2px solid var(--teal-200); }
 <ul class="booklist"> <li class="book"> <span class="book__info">The Catcher in the Rye | JD Salinger | 277 Pages</span> <button class="book__read-button">Unread</button> <button type="button" class="book__delete-button"> </button> </li> <li class="book"> <span class="book__info">Maid | A.Sommer | 277 Pages</span> <button class="book__read-button">Unread</button> <button type="button" class="book__delete-button"></button> </li> <li class="book"></li> </ul>

You can assign an eventListener to each button and trigger a function to handle the toggle classList and the button textContent, try this:您可以为每个按钮分配一个 eventListener 并触发一个函数来处理切换 classList 和按钮 textContent,试试这个:

 const readButtons = document.querySelectorAll(".book__read-button"); readButtons.forEach(readButton => { readButton.addEventListener("click", e => bookReaded(e)); }); function bookReaded(event) { console.log(event.target); event.target.classList.toggle('clicked'); event.target.textContent = event.target.textContent == 'Unread' ? 'Read' : 'Unread'; }
 .book__read-button.clicked { background-color: green; border: 2px solid var(--teal-200); }
 <ul class="booklist"> <li class="book"> <span class="book__info">The Catcher in the Rye | JD Salinger | 277 Pages</span> <button id="the-catcher" class="book__read-button">Unread</button> </li> <li class="book"> <span class="book__info">Maid | A.Sommer | 277 Pages</span> <button id="maid" class="book__read-button">Unread</button> </li> <li class="book"></li> </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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