[英]jQuery/Javascript - check if every element in a given array is within each of the others
我想我需要一些帮助。 我敢肯定有一个简单的解决方案,但我没有。
我在页面中有一个搜索框,它会自动显示FAQ问题,其中包含键入时的搜索条件。
这是我目前所拥有的:
var criteria = $('#search-criteria').val().toLowerCase().replace(/[^a-zA-Z 0-9]+/g," ");
$('.questions').each(function(){
if ($(this).text().toLowerCase().match(criteria)) {
$(this).attr('data-search','1');
} else {
$(this).attr('data-search','0');
}
});
它有效,但是问题是它将仅连续显示包含搜索条件的问题,即逐字显示。 我想将每个问题分成一个数组,并检查搜索条件中的每个单词在每个问题中是否都存在,从而使人们也可以搜索多个关键字而不是确切的短语。
我知道要将每个问题变成一个数组,我需要这样做:
$('.questions').each(function(){
var questionSplit = $(this).text().toLowerCase().replace(/[^a-zA-Z 0-9]+/g," ").split(" ");
// if all of the parts in the criteria array are found in the given question
// {
// $(this).attr('data-search','1');
// } else {
// $(this).attr('data-search','0');
// }
// }
这是我缺少的最后一个比较位。 任何帮助表示赞赏!
谢谢
我前一段时间已经为另一个项目写过这篇文章。
那这个呢:
$(table+" tbody td:MyCaseInsensitiveContains('"+val+"')").parent().show();
val
在哪里搜索...
抱歉,我忘了->您必须像这样扩展jquery:
$.extend($.expr[":"], {
"MyCaseInsensitiveContains": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
然后,您可以使用:MyCaseInsensitiveContains作为每个元素的伪类。
我的示例的窍门是:在表中显示所有内容。 如果用户搜索(变量val),则隐藏所有td`s,仅在搜索框中显示包含文本的内容。
您可以像这样遍历搜索值:
$(this).attr('data-search','0');
for (var i = 0; i < questionSplit.length; i++) {
if ($(this).text().toLowerCase().match(questionSplit[i])) {
$(this).attr('data-search','1');
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.