我建立了一个代码,该代码可以过滤数据直到第一次出现。之后,它将返回所有不需要的顺序数据。您能帮我解决问题的方法吗!
过滤器URL是localdirector / index.html?filter = code2。仅code2要返回的值。但对我来说,code3也正在返回。有人可以帮我吗!
<html>
<body>
<ul class="portfolio-filters list-inline">
<li class="filter active code1" data-filter="all">code1</li>
<li class="filter code2" data-filter="webdesign">code2</li>
<li class="filter code3" data-filter="responsive">code3</li>
<li class="filter code4" data-filter="wordpress">code4</li>
</ul>
<script>
const url = new URL(window.location.href)
const currentFilter = url.searchParams.get('filter')
if (currentFilter != null) {
const collection = document.getElementsByClassName('filter')
for (let item of collection) {
if (item.classList.contains(currentFilter)) {
item.style.display = 'block'
break
}
item.style.display = 'none'
}
}</script>
</body>
</html>
答案 0 :(得分:2)
退出循环,使循环之后的循环不运行
// const url = new URL(window.location.href)
const url = new URL('http://www.exaple.com/index.html?filter=code2')
const currentFilter = url.searchParams.get('filter')
if (currentFilter != null) {
const collection = document.getElementsByClassName('filter')
for (let item of collection) {
if (item.classList.contains(currentFilter)) {
item.style.display = 'block'
} else {
item.style.display = 'none'
}
}
}
<ul class="portfolio-filters list-inline">
<li class="filter active code1" data-filter="all">code1</li>
<li class="filter code2" data-filter="webdesign">code2</li>
<li class="filter code3" data-filter="responsive">code3</li>
<li class="filter code4" data-filter="wordpress">code4</li>
</ul>
您可以使用选择器而不是循环来实现
// const url = new URL(window.location.href)
const url = new URL('http://www.exaple.com/index.html?filter=code2')
const currentFilter = url.searchParams.get('filter') || 'code1';
document.querySelector(`.filter.${currentFilter}`).classList.add('active');
.filter {
display: none;
}
.filter.active {
display: block;
}
<ul class="portfolio-filters list-inline">
<li class="filter code1" data-filter="all">code1</li>
<li class="filter code2" data-filter="webdesign">code2</li>
<li class="filter code3" data-filter="responsive">code3</li>
<li class="filter code4" data-filter="wordpress">code4</li>
</ul>