我们如何使用jQuery根据下拉列表中的选定选项过滤下面的项目列表?
每个项目都有一个data-rel标签
<select id="lstkbCategory" data-placeholder="Choose a Category">
<option> --show all-- </option>
<option>close</option>
<option>general</option>
<option>verification</option>
<option>welcome</option>
</select>
<br>
<div class="kb-items">
<a class="kb-item" href="#" data-rel="verification">xxx</a>
<a class="kb-item" href="#" data-rel="close">xxx</a>
<a class="kb-item" href="#" data-rel="welcome">444</a>
<a class="kb-item" href="#" data-rel="welcome">aaa</a>
<a class="kb-item" href="#" data-rel="general">bbb</a>
<a class="kb-item" href="#" data-rel="general">ggg</a>
<a class="kb-item" href="#" data-rel="general">qqq</a>
<a class="kb-item" href="#" data-rel="general">sos</a>
</div>
答案 0 :(得分:2)
尝试
$("#lstkbCategory").change(function () {
var value = $(this).val();
$(".kb-items .kb-item").show();
if (value !== '-- show all --') { $(".kb-items .kb-item[data-rel !='" + value + "']").hide(); }
});
答案 1 :(得分:1)
您可以使用如下属性选择器:
var $relElements = $("[data-rel='" + selectedOption + "']");
(更多关于属性选择器:https://api.jquery.com/category/selectors/attribute-selectors/)
还有一种过滤方法可用于缩小元素组的范围:
$(".kb-item").filter("[data-rel='" + selectedOption + "']");
答案 2 :(得分:1)
$('#lstkbCategory').change(function() {
var value = $('option:selected', this).text();//get the text of selected option
$('.kb-items a').filter(function(i, v) {
$(v).removeClass('red')
return $(v).attr('data-rel') == value//compare the option with the data-rel
}).addClass('red')//addClass to anchor with matching data-rel to value
})
&#13;
.red {
display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lstkbCategory" data-placeholder="Choose a Category">
<option>--show all--</option>
<option>close</option>
<option>general</option>
<option>verification</option>
<option>welcome</option>
</select>
<br>
<div class="kb-items">
<a class="kb-item" href="#" data-rel="verification">xxx</a>
<a class="kb-item" href="#" data-rel="close">xxx</a>
<a class="kb-item" href="#" data-rel="welcome">444</a>
<a class="kb-item" href="#" data-rel="welcome">aaa</a>
<a class="kb-item" href="#" data-rel="general">bbb</a>
<a class="kb-item" href="#" data-rel="general">ggg</a>
<a class="kb-item" href="#" data-rel="general">qqq</a>
<a class="kb-item" href="#" data-rel="general">sos</a>
</div>
&#13;