我想通过jQuery做一些过滤器 这是我的HTML
<ul id="filters" class="filter nav nav-pills">
<li><a class="filter_link" href="#" data-category="7">Shop</a></li>
<li><a class="filter_link" href="#" data-category="8">Portal</a></li>
<li><a class="filter_link" href="#" data-category="9">Website</a></li>
</ul>
<div class="col-lg-3 filter_div" data-postcat="9">
some html
</div>
<div class="col-lg-3 filter_div" data-postcat="8">
some html
</div>
这是我的JS
jQuery(document).on('click', '.filter_link', function() {
var catId = jQuery(this).data("category");
jQuery('.filter_div').each(function(i, el) {
var termId = jQuery(el).data('postcat');
});
});
我无法理解如何通过点击隐藏和显示元素 如果我点击ul&gt; li> a具有属性,例如8.我想隐藏所有数据类别不是8的div
答案 0 :(得分:1)
您可以使用attribute selector
jQuery(document).on('click', '.filter_link', function() {
var catId = jQuery(this).data("category");
//use attribute selector to find the items to be shown
var $targets = jQuery('.filter_div[data-postcat="'+catId+'"]').show();
//hide all the other items
jQuery('.filter_div').not($targets).hide();
});
演示:Fiddle
答案 1 :(得分:0)
你可以这样做:
$(document).on('click', '.filter_link', function() {
var catId = $(this).data("category");
//hide all div
$('.filter_div').hide();
//show only specific div
$(".filter_div[data-postcat='" + catId +"']").show();
});
答案 2 :(得分:0)
您必须使用jQuery attribute selector
过滤列表的JavaScript
function showCategory(categoryId) {
var $allDivs = jQuery('.filter_div[data-postcat]');
var $selectedDiv = $allDivs.filter('[data-postcat='+categoryId+']');
$allDivs.hide();
$selectedDiv.show();
}
jQuery(document).on('click', '.filter_link', function(event) {
var categoryId = event.target.getAttribute('data-category');
showCategory(categoryId);
event.preventDefault();
});
HTML
<ul>
<li><a class="filter_link" href="#" data-category="7">Shop</a></li>
<li><a class="filter_link" href="#" data-category="8">Portal</a></li>
<li><a class="filter_link" href="#" data-category="9">Website</a></li>
</ul>
<div class="filter_div" data-postcat="9">
category 9
</div>
<div class="filter_div" data-postcat="8">
category 8
</div>
这是一个有效的JSFiddle:http://jsfiddle.net/pomeh/e04kxbhc/