我試圖找出一種方法,可以將類添加到目標元素,同時從另一個類中刪除類具有相同類的元素。添加一個類來定位目標,並從具有相同類名的其他元素中刪除類
到目前爲止我有這個代碼。代碼按照需要工作,但是它說這個對象是不確定的,我很困惑,爲什麼會這樣。有沒有更好的方法來做我想做的事情?
它必須在純香草的JavaScript。在此先感謝 HTML
<ul class="number-container"><li class="number-item"><span class="number number-active" data-number="zero"></span></li>
<li class="number-item"><span class="number" data-number="one">1</span></li>
<li class="number-item"><span class="number" data-number="two">2</span></li>
<li class="number-item"><span class="number" data-number="three">3</span></li>
<li class="number-item"><span class="number" data-number="four">4</span></li>
<li class="number-item"><span class="number" data-number="five">5</span></li>
<li class="number-item"><span class="number" data-number="six">6</span></li>
<li class="number-item"><span class="number" data-number="seven">7</span></li>
<li class="number-item"><span class="number" data-number="eight">8</span></li>
<li class="number-item"><span class="number" data-number="nine"></span></li>
</ul>
的Javascript
// store elements in dom
var numberButtons = document.querySelectorAll(".number");
// loop to add event listener to each button
for (var i = 0; i < numberButtons.length; i++) {
// add click event listener
numberButtons[i].addEventListener("click", changeButton);
}
function changeButton(e) {
// get dataset value
var target = e.target;
var targetDataset = e.currentTarget.dataset.number;
for (var i = 0; i <= numberButtons.length; i++) {
numberButtons[i].classList.remove("number-active");
if (targetDataset === "zero") {
target.classList.add("number-active");
} else if (targetDataset === "one") {
target.classList.add("number-active");
} else if (targetDataset === "two") {
target.classList.add("number-active");
} else if (targetDataset === "three") {
target.classList.add("number-active");
} else if (targetDataset === "four") {
target.classList.add("number-active");
} else if (targetDataset === "five") {
target.classList.add("number-active");
} else if (targetDataset === "six") {
target.classList.add("number-active");
} else if (targetDataset === "seven") {
target.classList.add("number-active");
} else if (targetDataset === "eight") {
target.classList.add("number-active");
} else if (targetDataset === "nine") {
target.classList.add("number-active");
}
}
}
我相信我需要數據編號,因爲按下按鈕時,它會將頁面移動到某個位置並顯示/隱藏其他元素。 – norrisollie
你最初的錯誤是''for(var i = 0; i <= numberButtons.length; i ++){',你需要一個'<',而不是'<='。 – Stephan
只需兩個註釋: 您不必在for循環中調用'target.classList.add(「number-active」);''。 'target'已經包含了單擊的元素,所以在for循環之外調用它就足夠了。 爲了識別點擊的按鈕,你可以修改你的'addEventListener'調用來包含'i'(類似於'changeButton.bind(null,i)',並將'changeButton'簽名改爲'function changeButton(selected,e)' [更新codepen](https://codepen.io/stephtr/pen/jwJKgJ)或通過'target.firstChild.nodeValue'確定按鈕的編號(內容)。 – Stephan