Javascript 使用jQuery根据用户输入筛选列表
我有一个歌曲列表,我希望用户能够通过在文本字段中键入来过滤它们。以下是我现在正在做的:Javascript 使用jQuery根据用户输入筛选列表,javascript,jquery,Javascript,Jquery,我有一个歌曲列表,我希望用户能够通过在文本字段中键入来过滤它们。以下是我现在正在做的: $("#filter_song_list").keyup(function() { var filter = new RegExp($(this).val(), "i"); $("ul.song_list a").each(function(){ if (!$(this).text().match(filter)) { $(this).hide();
$("#filter_song_list").keyup(function() {
var filter = new RegExp($(this).val(), "i");
$("ul.song_list a").each(function(){
if (!$(this).text().match(filter)) {
$(this).hide();
} else {
$(this).show();
}
});
});
实现您要求的最简单方法(在性能方面没有比您的解决方案更好)是: 将过滤器更改为用户输入,而不是正则表达式 将筛选行更改为:
if ($(this).text().toLowerCase().indexOf($.trim(filter.toLowerCase())) > -1) {
:
但是,您只是对字符串中的字符串进行不区分大小写的搜索。这不需要正则表达式。@我觉得更适合你
我想说jQuery非常适合您,但它区分大小写。首先,对元素进行缓存引用以加快速度:
var cache = $("ul.song_list a");
然后使用jQueryfilter()
函数和hide()
匹配的元素进行简单的字符串匹配:
cache.filter(function ()
{
return $(this).text().toLower().indexOf( <value from input> ) < 1;
}).hide();
cache.filter(函数()
{
返回$(this.text().toLower().indexOf()<1;
}).hide();
最后一段代码:
$(function ()
{
var cache = $("ul.song_list a");
$("#filter_song_list").keyup(function ()
{
var val = $(this).val();
cache.filter(function ()
{
return $(this).text().toLower().indexOf(val) < 1;
})
.hide();
});
});
$(函数()
{
变量缓存=$(“ul.song_列表a”);
$(“#筛选#歌曲列表”).keyup(函数()
{
var val=$(this.val();
cache.filter(函数()
{
返回$(this.text().toLower().indexOf(val)<1;
})
.hide();
});
});
它认为您需要使用user.toLowerCase()来代替。另外,trued()和我将所有项目隐藏起来,并且不再显示,即使输入与文本匹配。你确定它能用吗?我做错什么了吗?
$(function ()
{
var cache = $("ul.song_list a");
$("#filter_song_list").keyup(function ()
{
var val = $(this).val();
cache.filter(function ()
{
return $(this).text().toLower().indexOf(val) < 1;
})
.hide();
});
});