[英]Filter a list based on user input with jQuery
I have a list of songs, and I want users to be able to filter them by typing into a text field. 我有一个歌曲列表,我希望用户能够通过在文本字段中键入来过滤它们。 Here's what I'm doing now:
这是我现在正在做的事情:
$("#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();
}
});
});
the easiest way to do what you ask for (not any better in terms of performance then your solution) is: 做您想要的事情的最简单方法(就性能而言,没有比您的解决方案更好的方法)是:
change filter to be the user input, not a regex. 将过滤器更改为用户输入,而不是正则表达式。
change the filtering line to: 将过滤线更改为:
if ($(this).text().toLowerCase().indexOf($.trim(filter.toLowerCase())) > -1) {
Escape your regex prior to executing it : 在执行前转义正则表达式 :
var pattern = $(this).val().replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
var filter = new RegExp(pattern , "i");
However you're just doing a case-insensitive search for a string within a string. 但是,您只是在对字符串中的字符串进行不区分大小写的搜索。 You don't need regular expressions for this.
您不需要为此使用正则表达式。 @ mkoryak's answer is more suitable for you IMO.
@mkoryak的答案更适合您IMO。
I'd have said jQuery's built-in contains
psuedo selector was perfect for you, but it is case sensitive. 我曾经说过jQuery的内置
contains
psuedo选择器非常适合您,但它区分大小写。
First of all, make a cached reference to your elements to speed things up: 首先,对元素进行缓存引用以加快处理速度:
var cache = $("ul.song_list a");
Then do a simple string match, using the jQuery filter()
function, and hide()
matched elements: 然后,使用jQuery
filter()
函数和hide()
匹配的元素进行简单的字符串匹配:
cache.filter(function ()
{
return $(this).text().toLower().indexOf( <value from input> ) < 1;
}).hide();
The final snippet of code: 最后的代码片段:
$(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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.