问题
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.
回答1:
Something like this: 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();
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)
.
回答2:
You can make use of the filter
method as already mentioned. Or you can easily extend jQuery with your own custom filter which is great way to reuse code.
$.expr[':'].containsWord = function(elem, index, match) {
var text = $(elem).text();
return !!text.match(new RegExp('\\b' + match[3] + '\\b'));
};
and now use it like you would do with any other built-in filter :containsWord('Some word')
.
See http://jsfiddle.net/U8T8p/9/
回答3:
Try something like this: http://jsfiddle.net/U8T8p/5/
$(list).find("a").filter(function() { return $(this).text() != filter; }).parent().slideUp();
$(list).find("a").filter(function() { return $(this).text() === filter; }).parent().slideDown();
回答4:
You can use .filter
to check the texts and slide these elements down, and pass these elements as a jQuery object to .not
to get the other elements to slide up: http://jsfiddle.net/U8T8p/8/.
(function($) {
$('.filterinput').keyup(function() {
var filter = $(this).val();
if (filter.length > 2) {
var a = $(list).find("a");
var x = a.filter(function() {
return $(this).text() === filter;
});
x.parent().slideDown();
a.not(x).parent().slideUp();
} else {
$(list).find("li").slideDown();
}
return false;
})
}(jQuery));
来源:https://stackoverflow.com/questions/8688929/how-to-make-a-simple-jquery-filter-list-accept-only-whole-words-so-it-doesnt-m