我想在 jQuery 中创建一个过滤器函数。所以当有人点击一个类别时,它只会显示该类别的项目。 我编写了一些函数的代码,但我无法让它工作。
我想要的是检查类别列表中的 data-filter
是否等于 `data-cat.如果是这样,我想显示与公式匹配的帖子。
我做错了什么?
HTML:
<div class="grid_12" id="category-nav">
<ul id="category" class="list-of-links centered">
<li><a href="#" class="current-cat" data-filter="rondvaart">Rondvaart</a></li>
<li><a href="#" data-filter="wandelingen">Wandelingen</a></li>
<li><a href="#" data-filter="rondleidingen">Rondleidingen</a></li>
<li><a href="#" data-filter="groepsarrangementen">Groepsarrangementen</a></li>
</ul>
</div><!-- End div.grid_12 #category-nav -->
<article class="post" data-cat="wandelingen">
<header>
<p class="byline">Rondvaart</p>
<h2>Binnendieze</h2>
</header><!-- End header -->
</article><!-- End article.post -->
<article class="post" data-cat="rondleidingen">
<header>
<p class="byline">Rondvaart</p>
<h2>Binnendieze</h2>
</header><!-- End header -->
</article><!-- End article.post -->
<article class="post" data-cat="wandelingen">
<header>
<p class="byline">Rondvaart</p>
<h2>Binnendieze</h2>
</header><!-- End header -->
</article><!-- End article.post -->
<article class="post" data-cat="groepsarrangnementen">
<header>
<p class="byline">Rondvaart</p>
<h2>Binnendieze</h2>
</header><!-- End header -->
</article><!-- End article.post -->
j查询:
// Variable
var posts = $('#activiteiten .post');
posts.hide();
// Click function
$( "#category li a" ).click(function() {
// Get data of category
var customType = $( this ).data(); // category
console.log(customType);
console.log(posts.length); // Length of articles
$('#activiteiten .post').each(function() {
// Get data of item
data = posts.data();
console.log(data);
// If equal = show
if( data == customType ){
alert("equal");
}
});
});
最佳答案
如果你要过滤你的帖子,你需要 filter()
方法:
var posts = $('.post');
posts.hide();
$('#category li a').click(function() {
var customType = $( this ).data('filter');
posts
.hide()
.filter(function () {
return $(this).data('cat') === customType;
})
.show();
});
关于javascript - 如何过滤数据过滤器 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750803/