gpt4 book ai didi

javascript - 如何连接jquery内容中的两个过滤器?过滤器1和过滤器2连接结果

转载 作者:行者123 更新时间:2023-12-03 01:26:20 25 4
gpt4 key购买 nike

我是 jquery 的新手。我在 jquery 中创建了过滤器,我想将它们连接在一起以仅显示单击的内容。我怎样才能做到这一点?对不起,我的英语不好。我尝试了很多个小时,终于构建了这个:

$("button").click(function() {
var show = $(this).attr('class');
$('.post').each(function(){
$(this).show();
var test = $(this).attr('class');
if (test.indexOf(show) < 0) $(this).hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>FIRST</h2>
<div id='filter'>
<button class='all'>All</button>
<button class='1'>One</button>
<button class='2'>Two</button>
</div>
<h2>TWO</h2>
<div id='filter'>
<button class='all'>All</button>
<button class='aa'>Washington</button>
<button class='bb'>Philadelphia</button>
</div>

<br>
<div id='posts'>
<div class='all post 1 aa'>One Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
<div class='all post 2 bb'>Two Philadelphia</div>
<div class='all post 2 aa'>Two Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
<div class='all post 2 aa'>Two Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
</div>

最佳答案

请参阅逻辑中的注释,了解每个步骤正在执行的操作的详细信息。

$("button").click(function() {
//remove the selected class from the previously selected button
$(this).closest('.filter').find('button.selected').removeClass('selected');
//put the class on the button you clicked
$(this).addClass('selected');

//get the data-filter off of the selected buttons and join them into a selector
var filter = '.'+ $('button.selected').map(function(){
return $(this).data('filter');
}).get().join('.');

//hide all the posts, and then show those that match
$('.post').hide().filter(filter).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>FIRST</h2>
<!-- we use a class because an id cannot be repeated
and we want to select both our filters later -->
<div class='filter'>
<!-- data fields let us separate the classes from the data that
is used for the filter -->
<button data-filter='all'>All</button>
<button data-filter='1'>One</button>
<button data-filter='2'>Two</button>
</div>
<h2>TWO</h2>
<div class='filter'>
<button data-filter='all'>All</button>
<button data-filter='aa'>Washington</button>
<button data-filter='bb'>Philadelphia</button>
</div>

<br>
<div id='posts'>
<div class='all post 1 aa'>One Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
<div class='all post 2 bb'>Two Philadelphia</div>
<div class='all post 2 aa'>Two Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
<div class='all post 2 aa'>Two Washington</div>
<div class='all post 1 bb'>One Philadelphia</div>
</div>

关于javascript - 如何连接jquery内容中的两个过滤器?过滤器1和过滤器2连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51527603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com