如何使一个简单的jQuery过滤器列表仅接受整个单词,因此它不匹配部分单词,而仅匹配整个单词 [英] How to make a simple jQuery filter list accept only whole words, so it doesn't match partial words, only whole words
问题描述
http://jsfiddle.net/nicktheandroid/U8T8p/4/
(function($) {
$('.filterinput').keyup(function() {
var filter = $(this).val();
if (filter.length > 2) {
// this finds all links in the list that contain the input,
// and hide the ones not containing the input while showing the ones that do
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
}(jQuery));
这将根据您输入的内容是否与列表中单词的任何部分匹配来过滤列表.我试图使它只匹配整个单词,因此直到输入完整单词之前它都不会匹配.正则表达式会是最好的吗?或者?我需要帮助,我尝试过的所有方法都没有效果.
This will filter the list based on if what you've typed matches ANY part of a word in the list. I'm trying to make it only match whole words, so it wont say it has a match until the full word is typed. Would Regex be best? Or? I need help, nothing I've tried has worked.
推荐答案
类似这样的内容: http://jsfiddle .net/U8T8p/10/
var containing = $('#list li').filter(function () {
var regex = new RegExp('\\b' + a, 'i');
return regex.test($('a', this).text());
}).slideDown();
$('#list li').not(containing).slideUp();
正则表达式限制与当前输入的文本以单词边界开头的限制匹配.因此,输入"Stat"后,您仍然会匹配"United States".您可以通过更改为RegExp('\\b' + a + '\\b', i)
使其与完整单词匹配.
The regex limits matches to those where the currently entered text starts at a word boundary. So, having typed 'Stat' you'd still match 'United States'. You can make it match a full word by changing to RegExp('\\b' + a + '\\b', i)
.
这篇关于如何使一个简单的jQuery过滤器列表仅接受整个单词,因此它不匹配部分单词,而仅匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!