我有一个可以是动态数组的数组,在我的html页面中,将有多个ul
和li
元素。我想搜索li
元素的每个ul
,如果li文本出现在我的数组中,则显示ul,否则隐藏该特定ul。
$(function() {
var filter_array = ['item2', 'item3', 'item28'];
$('ul li').each(function() {
var jThis = $(this);
var current_ul = jThis.attr('data-currentul');
var current_text = jThis.text();
if ($.inArray(current_text, filter_array)) {
console.log("CurrentUL:" + current_ul + " current_text:" + current_text + " ISpresent : Yes");
$('.ul' + current_ul).show();
} else {
console.log("CurrentUL:" + current_ul + " current_text:" + current_text + " ISpresent : No");
$('.ul' + current_ul).hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="category1" class="ul1">
<li data-currentul="1">item1</li>
<li data-currentul="1">item2</li>
<li data-currentul="1">item3</li>
</ul>
<ul class="ul2">
<li data-currentul="2">item27</li>
<li data-currentul="2">item28</li>
</ul>
<ul class="ul3">
<li data-currentul="3">item29</li>
<li data-currentul="3">item30</li>
</ul>
预期输出:
item1
item2
item3
item27
item28
请参考jsfiddle代码:JSFiddleCode
答案 0 :(得分:1)
如果未找到元素的索引,则应使用.filter()
,$.inArray()
返回-1
。
此外,您可以使用DOM关系来定位要显示的UL
元素,而不是使用ID选择器
$(function() {
var filter_array = ['item2', 'item3', 'item28'];
var ul = $('ul');
//Start Hidden
ul.hide();
//filter UL element
ul.filter(function() {
//Get LI elements matching the criteria
var liHavingText = $(this).find('li').filter(function() {
return $.inArray($.trim($(this).text()), filter_array) > -1; //Compare with index
});
return liHavingText.length > 0;
}).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="category1" class="ul1">
<li data-currentul="1">item1</li>
<li data-currentul="1">item2</li>
<li data-currentul="1">item3</li>
</ul>
<ul class="ul2">
<li data-currentul="2">item27</li>
<li data-currentul="2">item28</li>
</ul>
<ul class="ul3">
<li data-currentul="3">item29</li>
<li data-currentul="3">item30</li>
</ul>
答案 1 :(得分:1)
您可以遍历数组项,并检查每个li
的文本是否与数组项匹配,例如:
var filter_array = ['item2','item3','item28'];
filter_array.forEach(text => {
$('li').each(function(index, elem){
if($(elem).text().trim() == text) {
$(elem).parent().show();
return false;
}
});
});
$(function(){
var filter_array = ['item2','item3','item28'];
filter_array.forEach(text => {
$('li').each(function(index, elem){
if($(elem).text().trim() == text) {
$(elem).parent().show();
return false;
}
});
});
});
ul {display: none;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ul id="category1" class="ul1">
<li data-currentul="1">item1</li>
<li data-currentul="1">item2</li>
<li data-currentul="1">item3</li>
</ul>
<ul class="ul2">
<li data-currentul="2">item27</li>
<li data-currentul="2">item28</li>
</ul>
<ul class="ul3">
<li data-currentul="3">item29</li>
<li data-currentul="3">item30</li>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</ul>
</body>
</html>