检查按钮的数据属性是否与post类相同



我试图通过向没有特定类别的元素添加一个隐藏类来创建一个post过滤器。我有多个具有"data thema"属性的按钮,我想检查单击按钮的属性值,并将其与post元素的类进行比较。当帖子没有等于datathema值的类时,我想向该元素添加一个隐藏类。

现在,当点击一个按钮时,所有帖子都会隐藏该类。这就是我想要的,但它需要检查是否有任何关于特定类的帖子,然后再次删除隐藏的类。

这就是我目前所拥有的:

jQuery

$('.intro .themaWrapper span').on('click', function() {
var clickedTheme = $(this).attr('data-thema');
$('.posts .post').each(function() {
// $(this).addClass('hidden');
if ($(this).hasClass(clickedTheme)) {
$(this).removeClass('hidden');
} else {
$('.posts .post').addClass('hidden');
}
});
});

PHP

foreach( $themas as $category ) {
if( $category->parent == 0 ) {
echo '<span class="btn blue" data-thema="'. esc_attr( $category->slug ) .'">';
echo $category->name;
echo '</span>';
}
}
while ( $query->have_posts() ) {
$query->the_post();
$f = get_fields();
$classes = '';
$terms = wp_get_post_terms( get_the_ID(), 'thema');
foreach($terms as $t) {
$classes .= $t->slug . ' ';
}
echo "<div class='post ". $classes ."'>";
echo "<h2>".get_the_title()."</h2>";
echo "</div>";
}

您可以将整个逻辑恢复为一个单链表达式:

$('span').on('click', function() {
$('.posts .post')
// Add the hidden class to all the posts
.addClass('hidden')
.removeClass('red')
// Filter those with the same thema
.filter('.' + $(this).data('thema'))
// Remove the hidden class for the filter results
.removeClass('hidden')
.addClass('red');
});
.posts {
margin-top: 20px;
}
.hidden {
display: none;
}
.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-thema="thema-1">Thema 1</span>
<span data-thema="thema-2">Thema 2</span>
<span data-thema="thema-3">Thema 3</span>
<div class="posts">
<div class="post thema-1">Thema 1 div</div>
<div class="post thema-3">Thema 3 div</div>
<div class="post thema-2">Thema 2 div</div>
<div class="post thema-2 thema-1">Thema 1 and Thema 2 div</div>
</div>

最新更新