我正在尝试使用 JQuery 使用下拉列表按类别进行过滤。我是新手,因此非常感谢您的帮助!
当您选择“类别 1 + 事物”时,它应该隐藏所有其他类别及其各自的事物。与其他下拉选项相同。在选择下拉项后切换下拉项时就会出现问题。我无法让隐藏的元素重新出现。感谢您的帮助!
<select id="categoryFilter">
<option selected="selected" disabled="disabled">Filter by...</option>
<option value="0">Show All Categories + Things</option>
<option value="1">Category 1 + Things</option>
<option value="2">Category 2 + Things</option>
</select>
<h1 class="category-1">Category 1</h1>
<div class="thing thing-category-1">
<span>thing 1</span>
</div>
<div class="thing thing-category-1">
<span>thing 2</span>
</div>
<div class="thing thing-category-1">
<span>thing 3</span>
</div>
<h1 class="category-2">Category 2</h1>
<div class="thing thing-category-2">
<span>thing 4</span>
</div>
<div class="thing thing-category-2">
<span>thing 5</span>
</div>
<div class="thing thing-category-2">
<span>thing 6</span>
</div>
这是 JavaScript:
$(document).ready(function() {
$('#categoryFilter').on('change', function() {
if($(this).val() == '1') {
$('h1:not(.category-1)').hide();
$('.thing:not(.thing-category-1)').hide();
}
if($(this).val() == '2') {
$('h1:not(.category-2)').hide();
$('.thing:not(.thing-category-2)').hide();
}
if($(this).val() == '0') {
location.reload();
}
});
});
演示: http://codepen.io/drews1949/pen/oBbGma?editors=1010
我是前端新手,所以感谢您的帮助!
最佳答案
通过 jQuery,您可以在 HTML 属性上使用 CSS 子字符串选择器。它们非常有用,并且不需要您更改命名约定或任何 HTML。
编辑:最终,如果您编写自己的 HTML,这有点多余,更好的方法是将您的分类项包装在其自己的父元素中,而不是单独命名所有内容.
这是一个例子
// Always cache DOM queries
// returns all elements with class ending in "category-1"
var $opt1 = $('[class$="category-1"]')
// returns all elements with class ending in "category-2"
var $opt2 = $('[class$="category-2"]')
var $selector = $('#categoryFilter')
window.onload = init()
function init(){
$selector.on('change',function(){
if($selector.val()==0){$opt2.show();$opt1.show()}
if($selector.val()==1){$opt1.show();$opt2.hide()}
if($selector.val()==2){$opt2.show();$opt1.hide()}
})
}
<select id="categoryFilter">
<option selected="selected" disabled="disabled">Filter by...</option>
<option value="0">Show All Categories + Things</option>
<option value="1">Category 1 + Things</option>
<option value="2">Category 2 + Things</option>
</select>
<h1 class="category-1">Category 1</h1>
<div class="thing thing-category-1">
<span>thing 1</span>
</div>
<div class="thing thing-category-1">
<span>thing 2</span>
</div>
<div class="thing thing-category-1">
<span>thing 3</span>
</div>
<h1 class="category-2">Category 2</h1>
<div class="thing thing-category-2">
<span>thing 4</span>
</div>
<div class="thing thing-category-2">
<span>thing 5</span>
</div>
<div class="thing thing-category-2">
<span>thing 6</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
关于javascript - 如何使用下拉菜单返回 JQuery 隐藏的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579704/