[英]How to filter on data-filter jQuery
我想在jQuery中創建一個過濾函數。 因此,當有人點擊某個類別時,它只會顯示該類別的項目。 我有一些函數代碼,但我不能讓它工作。
我想要的是檢查類別列表中的data-filter
是否等於`data-cat。 如果是這樣,我想顯示與formule相匹配的帖子。
我錯了什么?
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");
}
});
});
如果您要過濾帖子,則需要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();
});
演示: http : //jsfiddle.net/FSLXT/
tomType = $( this ).data();
1)錯過了在這里添加過濾器/ cat屬性
tomType = $( this ).data('filter');
data = posts.data('cat');
2)你也錯過了一個id為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
}
});
希望你明白。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.