簡體   English   中英

我有一些按鈕,我需要在點擊時將一個紅色變為紅色,而舊的紅色按鈕變為灰色,我該怎么做?

[英]I have some buttons, i need to turn one red on click and old red button grey how do i do this?

Html:

<div class="buttons">
    <form>
        <button class="all active" type="button">All</button>
        <button class="print-temp" type="button">Print template</button>
        <button class="web-temp" type="button">Web template</button>
        <button class="user-inter" type="button">user interface</button>
        <button class="mock-up" type="button">mock-up</button>
    </form>
</div>

JS:

let buttons = document.querySelectorAll(".buttons form button");
for(let button of buttons) {
console.log(button);
button.onclick = function() {
    buttons.classList.remove("active") //making old active button not active
    button.classList.add("active") //making new active button
};
console.log(button);
}

每次我點擊任何按鈕我都會得到這個:

Uncaught TypeError: Cannot read property 'remove' of undefined
at HTMLButtonElement.button.onclick (main.js:8)

怎么了? 是“.buttons 表單按鈕”嗎?

檢查是否有任何按鈕active了 class。 如果是這樣,則使用remove刪除 class。

這里的buttons buttons.classList.remove("active")指的是集合而不是單個元素

 let buttons = document.querySelectorAll(".buttons form button"); for (let button of buttons) { button.onclick = function() { const getActiveBtn = document.querySelector('button.active'); if (getActiveBtn) { getActiveBtn.classList.remove("active") } button.classList.add("active") }; }
 .active { background: red; color:#fff; }
 <div class="buttons"> <form> <button class="all active" type="button">All</button> <button class="print-temp" type="button">Print template</button> <button class="web-temp" type="button">Web template</button> <button class="user-inter" type="button">user interface</button> <button class="mock-up" type="button">mock-up</button> </form> </div>

暫無
暫無

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

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