我目前正在嘗試設定一系列按鈕的樣式,以便在單擊時它們會更改為不同的樣式并且文本內容也會更改。它正在作業,除了當我單擊具有相同類的另一個按鈕時,另一個按鈕失去其 classList 切換。這一切都有效,直到我按下下一個元素上的按鈕,并且需要它們獨立作業,因為它們被用來標記這本書是否已被閱讀。
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 | J. D. 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>
uj5u.com熱心網友回復:
您可以為每個按鈕分配一個 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 | J. D. 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/496771.html
標籤:javascript html css
上一篇:如何總結在提示中輸入的所有數字