假設我有一個這樣的排序串列
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<div class="dropdown">
<button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Tomato</a>
<a href="#">APPle</a>
<a href="#">Carrot</a>
<a href="#">Broccoli</a>
</div>
</div>
我希望該下拉串列對專案串列進行排序并隱藏其他專案,
例如,如果我有這個串列
<ul>
<li>Tomato</li>
<li>APPle</li>
<li>Broccoli</li>
<li>Carrot</li>
<li>Tomato</li>
<li>Broccoli</li>
</ul>
并且用戶點擊下拉串列中的番茄,所有專案都應該被隱藏,只顯示番茄元素。這樣做的正確方法是什么?知道排序下拉串列會很長。
uj5u.com熱心網友回復:
您可以添加一個click事件偵聽器,所有選擇的選項,通過每個回圈li中ul和皮張那些textContent不等于textContent點擊選擇選項。
const options = document.querySelectorAll('.dropdown .dropdown-content a')
const listItems = document.querySelectorAll('#list li');
options.forEach(f => f.addEventListener('click', function(e){
let text = this.textContent;
listItems.forEach(e => e.style.display = e.textContent == text ? "block" : "none")
}))
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<div class="dropdown">
<button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Tomato</a>
<a href="#">APPle</a>
<a href="#">Carrot</a>
<a href="#">Broccoli</a>
</div>
</div>
<ul id="list">
<li>Tomato</li>
<li>APPle</li>
<li>Broccoli</li>
<li>Carrot</li>
<li>Tomato</li>
<li>Broccoli</li>
</ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323885.html
