2 回答
TA贡献1830条经验 获得超3个赞
请参阅我的示例,我设置了与目标相等的最小变化,并略微减少了代码:
const buttons = Array.from(document.querySelector("#buttons").children)
const items = Array.from(document.querySelector(".artists-container").children)
const onClick = function() {
buttons.forEach((button)=>{ button.classList.remove("active") })
this.classList.add("active")
const target = this.getAttribute("data-target")
items.forEach((item)=>{ item.style.display="none" })
items.filter(item=>item.getAttribute("data-discipline").indexOf(target)>=0 || target=="artists").forEach((item)=>{item.style.display="block"})
}
buttons.forEach((button)=>{ button.addEventListener("click",onClick) })
在操场上查看完整示例:https://jsfiddle.net/denisstukalov/uz5qeoLy/9/#&togetherjs=LpfzceeTVL
TA贡献1796条经验 获得超4个赞
我认为最简单的解决方案是使用 检查目标是否在属性列表中。includes
const buttons = [...document.querySelector("#buttons").children]
const items = [...document.querySelector(".artists-container").children]
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
buttons.forEach(button => button.classList.remove("active"))
this.classList.add("active")
const target = this.getAttribute("data-target")
items.forEach(item => {
let display = target === "artists" ? "block" : "none"
if (item.getAttribute("data-discipline").includes(target)) {
display = "block"
}
item.style.display = display;
});
});
}
<section class="artists">
<div class="filter-btn">
<ul id="buttons">
<li class="active" data-target="artists">All</li>
<li data-target="category1">Category 1</li>
<li data-target="category2">Category 2</li>
<li data-target="category3">Category 3</li>
</ul>
</div>
<div class="artists-container">
<article data-discipline="category1 category2">
<a href="#">
<div class="artist-details">
<p>Category 1, Category 2</p>
<h5>I appear in two categories</h5>
</div>
</a>
</article>
<article data-discipline="category3">
<a href="#">
<div class="artist-details">
<p>Category 3</p>
<h5>I appear in one category</h5>
</div>
</a>
</article>
</div>
</section>
添加回答
举报