[英]Changing JavaScript function to work with multiple check boxes to accept terms and conditions
[英]Searching with Jquery - Work for multiple terms
我在網上找到了一個可搜索的常見問題解答片段。 但是,我想知道是否有人知道如何對其進行修改以使用多個術語。
在上面的示例中,我想輸入“ paper Earth”以返回兩個示例結果。 如果我現在輸入,它不會返回任何內容。 我想我要使其等同於搜索“紙張”或“地球”。
任何幫助將非常感激。
詹姆士
您可以做的是將搜索字符串與正則表達式匹配以獲取所有單詞。 然后,對於每個li
您檢查其文本是否包含任何單詞,並適當顯示或隱藏。 我已經使用了array.some
,但這僅在更新的瀏覽器中可用。
我也整理了一下-並非所有代碼都是必需的: http : //jsfiddle.net/pT6dB/29/ 。
// no need for preventDefault here - clicking a <strong> doesn't do anything
$('li strong').click(function(e) {
$(this).parent().find('em').slideToggle();
});
// the "input" event is available on newer browsers, and is also fired when e.g.
// pasting or dragging text
$('#search').on("input", function(e) {
// make it case-insensitive, and match against a regexp that matches
// non-space characters
var words = $(this).val().toLowerCase().match(/\S+/g);
if (!words) { // no match, i.e. no words found
$('#result li').show();
} else {
$('#result li').each(function() {
var text = $(this).text().toLowerCase();
var show = words.some(function(word) {
return ~text.indexOf(word); // ~ with indexOf means "contains"
});
$(this).toggle(show); // will show or hide depending on "show"
});
}
});
您需要使用javascript string.split函數將值除以“”字符。 然后遍歷每個元素以查看是否存在匹配項。
例如:
$('#search').keyup(function(e) {
var s = $(this).val().trim();
if (s === '') {
$('#result LI').show();
return true;
}
$('#result LI').hide();
splits = s.split(" ");
for(x in splits){
$('#result LI:contains(' + splits[x]+ ')').show();
}
return true;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.