我實際上是在單擊時嘗試將類(選定)添加到 li 并從鄰居 li 中洗掉類。
問題是當有 2 個 ul 時它不起作用,下面的代碼僅適用于第一個 ul 或者當我單擊第二個 li 的 li 時,第一個 li 活動被洗掉
const menuLis = document.querySelectorAll("#top-nav > li");
for (let li of menuLis) {
li.addEventListener("click", function(){
// 1. Remove Class from All Lis
for (let li of menuLis) {
li.classList.remove('selected');
}
// 2. Add Class to Relevant Li
this.classList.add('selected');
});
}
.selected{color:red}
<ul id='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul id='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
感謝您的幫助
uj5u.com熱心網友回復:
您需要使用一個類,以及為每個 ul 單獨處理以使其正常作業:
const menuUls = document.querySelectorAll('.top-nav');
for (const ul of menuUls) {
const menuLis = ul.querySelectorAll('li');
for (const li of menuLis) {
li.addEventListener('click', function () {
// 1. Remove Class from All Lis
for (let li of menuLis) {
li.classList.remove('selected');
}
// 2. Add Class to Relevant Li
this.classList.add('selected');
});
}
}
.selected{color:red}
<ul class='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul class='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
uj5u.com熱心網友回復:
您可以選擇元素的siblings,然后洗掉selected類。
const menuLis = document.querySelectorAll(".top-nav > li");
for (let li of menuLis) {
li.addEventListener("click", function(){
for (let sibling of this.parentNode.children) {
sibling.classList.remove('selected');
}
this.classList.add('selected');
});
}
.selected{color:red}
<ul class='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul class='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
uj5u.com熱心網友回復:
Id 必須是唯一的——每頁一個,所以你應該使用一個類來代替。
另一件要考慮的事情是:在每次點擊時,您都會向所有串列項添加新的偵聽器,這對于一個小例子來說可能沒問題,但在規模上可能會證明效率低下。
另一種方法是使用事件委托——將一個偵聽器附加到每個父元素、串列項,并檢查事件目標上的資訊以更新其串列項。
const menus = document.querySelectorAll('.top-nav');
menus.forEach(menu => {
menu.addEventListener('click', handleClick, false);
});
function handleClick(e) {
const { nodeName, parentNode } = e.target;
// If the clicked element is a list item
if (nodeName === 'LI') {
// Find all the list items of the current list
const items = parentNode.querySelectorAll('li')
// Remove the class from each, and then add the
// class to the element that was clicked
items.forEach(i => i.classList.remove('selected'));
e.target.classList.add('selected');
}
}
.selected { color:red; }
li:hover { cursor: pointer; }
<ul class="top-nav">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul class="top-nav">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
附加檔案
- 解構賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/357923.html
標籤:javascript html css
上一篇:使用react-router-dom在Route中添加一個組件作為props
下一篇:回圈顏色
