我有一个搜索字段,我在其中输入标签(多个标签逗号分隔)
我希望在div数据属性中找到每个标记,如果找到,则显示该div,否则将其隐藏。
HTML代码
<div class="profile-listing">
<div data-tag="a b" class="profile"></div>
<div data-tag="b c" class="profile"></div>
<div data-tag="a c" class="profile"></div>
<div data-tag="d c" class="profile"></div>
</div>
jQuery("#search_tag").keyup(function(){
var string_filter = jQuery(this).val();
var array_filter = string_filter.split(',');
var filter = jQuery(this).val(), count = 0;
jQuery(".profile_listing .profile").each(function(){
jQuery.each( array_filter, function( intValue, currentFilter ) {
if(jQuery(".profile").indexOf(currentFilter) >-1){jQuery(this).show(); }else{
jQuery(this).hide();
}
});
});
});
案例:
如果我在搜索字段"a“中输入,则包含数据标记值"a”div应显示为配置文件div (1,3),如果我输入a,b,则应显示div number (1,2,3)。
任何jquery过滤器帮助。
谢谢
发布于 2019-01-29 19:05:26
您可以遍历dom元素来实现这一点。
这里用到的概念是
- each循环在此here上执行更多操作
此here上的字符串比较详细信息
JavaScript在此here上拆分的更多信息
// this is your input
var input = 'a,b';
// Split the input by comma
var profileSplit = input.split(',');
// iterate through all div which has class 'profile'
$('.profile').each(function(i, obj) {
// hide the objects by default
$(obj).hide();
// retrive the data-tag value
var tagVal = $(obj).data('tag');
// iterate through your 'input' which as split by , earlier
profileSplit.forEach(function(item) {
//check if 'data-tag' value with the input
if (tagVal.indexOf(item) >= 0) {
// show the div. 'obj' is the reference to the current div iteration
$(obj).show();
console.log(tagVal)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<div class="profile-listing">
<div data-tag="a b" class="profile">one</div>
<div data-tag="b c" class="profile">two </div>
<div data-tag="a c" class="profile">three</div>
<div data-tag="d c" class="profile">four</div>
</div>
https://stackoverflow.com/questions/54419170
复制相似问题