【发布时间】:2019-04-01 09:48:09
【问题描述】:
我有这段代码,但它不能正常工作。
let productBox = document.querySelectorAll('.product');
let selectCategory = document.querySelector('#select-category');
let categoryVal = document.querySelectorAll('#select-category option');
selectCategory.addEventListener('change', () => {
Array.prototype.forEach.call(categoryVal, catItem => {
Array.prototype.forEach.call(productBox, prodItem => {
if((catItem.selected) && (prodItem.category ===
catItem.category)) {
prodItem.style.display = 'none'
}
})
})
})
.product {
border: 1px solid;
padding: 2px;
margin: .5rem;
}
<select id="select-category">
<option category="all">All</option>
<option category="dinner">Dinner</option>
<option category="first meal">First meal</option>
<option category="garnish">Garnish</option>
</select>
<div category="dinner" class="product">Dinner</div>
<div category="first meal" class="product">First meal</div>
<div category="garnish" class="product">Garnish</div>
我需要在选择option 元素时,display none 应用于类别不匹配的块。最好的方法是什么?
【问题讨论】:
-
为什么不向所有其他 div 显示:none,除了选中的那个。这里需要搜索什么? (我假设只有 3 个 div)
-
必须只显示类别属性与所选
option的类别属性重合的div,其他全部隐藏
标签: javascript html ecmascript-6