按包含字符串的data-attr过滤div [英] Filter divs by data-attr containing string
问题描述
如何使用jQuery基于其自定义data
属性中的div过滤多个div?问题在于该属性可以有多个值(被视为1个字符串).因此,我需要确定data-att
值是否包含字符串.
How to filter a number of divs based on what they have in their custom data
attribute using jQuery? The problem is that the attribute can have more than 1 values (which is treated as 1 string). So I need to work out if the data-att
value contains a string.
<a href="">small</a>
<a href="">medium</a>
<a href="">large</a>
<div class="size" data-size="small">small tee</div>
<div class="size" data-size="small medium">small tee</div>
<div class="size" data-size="small medium">small tee</div>
<div class="size" data-size="small">small tee</div>
<div class="size" data-size="medium large">small tee</div>
<div class="size" data-size="medium large">small tee</div>
因此,如果单击了小链接,则应该仅显示其数据大小值包含小(即小"和小中")的div.
So if small link is clicked it should show only the divs whose data-size value contains small, so 'small' and 'small medium'.
我尝试过:
$("a").click(function(e) {
var selectSize = $(this).text();
filter(selectSize)
e.preventDefault();
});
function filter(e){
$('.tyre').hide()
.filter('[data-sizes=""]:contains(' + e + ')')
.show(); // show the filtered elements
}
但不行.
推荐答案
Arun P Johny的答案很完美.我接受了他的解决方案,并进行了一些调整,使其更加笼统.
Arun P Johny's answer is perfect. I took his solution and tweak a little to make it more general.
您可以使用它来匹配字符串的一部分,而不仅仅是整个单词.将来可能会派上用场.
You can use it to match part of the string, not just the whole word. Might come in handy in the future.
$("#filter").keyup(function(){
var selectSize = $(this).val();
filter(selectSize);
});
function filter(e) {
var regex = new RegExp('\\b\\w*' + e + '\\w*\\b');
$('.size').hide().filter(function () {
return regex.test($(this).data('size'))
}).show();
}
<input type='text' id='filter'>
<div class="size" data-size="small">small tee</div>
<div class="size" data-size="small medium">small medium tee</div>
<div class="size" data-size="small medium tee">small medium tee</div>
<div class="size" data-size="small">small tee</div>
<div class="size" data-size="medium large">medium large tee</div>
<div class="size" data-size="medium large">medium large tee</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
或者尝试以下 FIDDLE
这篇关于按包含字符串的data-attr过滤div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!