我有此代码,但无法正常工作。
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
应用于其类别不匹配的块。做这个的最好方式是什么? 最佳答案
它的工作正常。让我知道你的期望吗
<script>
let productBox = document.querySelectorAll('.product');
let selectCategory = document.querySelector('#select-category');
let categoryVal = document.querySelectorAll('#select-category option');
selectCategory.addEventListener('change', (evt) => {
var selectedValue = evt.currentTarget.value.toLowerCase();
Array.prototype.forEach.call(productBox, prodItem => {
if(selectedValue !== 'all' && (prodItem.getAttributeNode('category').value !==
selectedValue)) {
prodItem.style.display = 'none'
} else {
prodItem.style.display = 'block'
}
});
});
</script>
关于javascript - 如何最好地在js上对产品进行排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55452235/