$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).html();
if (tmpHTML == tmpVAL) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});而#addSearch是一个<input type="text">。
所以,我的问题是;这显然只会返回与tmpVAL完全匹配的结果-我如何允许它,这样每个字母都会改变搜索结果。
例如:
I键入N
它提供了No, Not, Nothing, Nothingness
I键入NOT
它提供了Not, Nothing, Nothingness
任何帮助都将不胜感激,我想应该是RegEx吧?
发布于 2011-02-17 07:27:02
您可以使用正则表达式,但我认为这可能有些过分了。你可以直接使用indexOf
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
$('.w').each(function() {
var tmpHTML = $(this).html().toLowerCase();
if (tmpHTML.indexOf(tmpVAL) >= 0) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});工作示例:http://jsfiddle.net/andrewwhitaker/PRyvU/
这里有一个不使用.each()的替代解决方案
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
var $words = $(".w");
var contains = function(haystack, needle) {
return haystack.indexOf(needle) >= 0;
};
if (tmpVAL.length < 1) {
$words.fadeIn(250);
}
else {
$words.filter(function() {
return !contains($(this).html().toLowerCase(), tmpVAL);
}).fadeOut(250);
$words.filter(function() {
return contains($(this).html().toLowerCase(), tmpVAL);
}).fadeIn(250);
}
});http://jsfiddle.net/andrewwhitaker/EyJ6b/
发布于 2011-02-17 07:59:15
$(function() {
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).text();
var subSection = tmpHTML.substring(tmpVAL.length, 0);
if (subSection == tmpVAL && tmpVAL != '' ) {
$(this).show();
} else {
$(this).hide();
}
});
});
});https://stackoverflow.com/questions/5020940
复制相似问题