我想在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 -->
JQUERY:
// 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");
}
});
});
答案 0 :(得分:3)
如果您要过滤帖子,则需要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();
});
答案 1 :(得分:2)
tomType = $( this ).data();
1)错过了在这里添加 filter / cat 属性
tomType = $( this ).data('filter');
data = posts.data('cat');
2)你也错过了一个标识为activiteiten
的元素,因此下面的代码失败了。
var posts = $('#activiteiten .post'); //change as var posts = $('.post')
posts.hide();
data = posts.data();
3)这是一种必须的方式
$('.post').each(function () {
data = $(this).data('cat');
// If equal = show
if (data == customType) {
alert("equal");
$(this).show(); //show the matched element
}
});