【发布时间】:2013-08-02 23:26:26
【问题描述】:
我需要创建一个正则表达式函数来过滤包含所选字符串的文章提要列表。
当用户单击过滤器选项时,下面的代码会将所选字符串添加到变量“tf”中。变量“tf”可能如下所示:“香草冰淇淋,视频游戏”,其中“香草冰淇淋”和“视频游戏”是关键字。
$(".trending").click(function(){
$(this).toggleClass("selected");
var temp22 = "";
$(".trending.selected").each(function(i, e) {
temp22 += $(this).attr("id").substr(9) + ", ";
});
tf = temp22;
filter_trend();
});
下面的代码通过搜索文章列表来过滤文章提要,以查看它是否包含关键字。 $(f2) 是文章列表,我通过仅返回其 html 中包含关键字的文章来过滤它。
function filter_trend(){
var tfilter = new RegExp (tf, "i");
if (tf == ""){
filter_load();
return;
}
if (f == "")
var f2 = ".article";
else
var f2 = f;
$(f2).hide();
//alert(f2);
$(f2).filter(function(i,e) {
return i < list_length && tfilter.test($(e).html());
}).show();
}
有没有办法使用正则表达式或者我应该用另一种方法来解决这个问题?
【问题讨论】:
-
既然可以使用
.indexOf,为什么还要使用正则表达式? jsfiddle.net/d2M5n -
顺便说一句,当您可以将
tf作为函数参数传递给filter_trend()时,依赖全局变量来传递信息并不是一个很好的做法。
标签: javascript jquery regex web