在我的 HTML 中有许多 div,每个里面都有名字。我必须在其中实现字母过滤器。如果用户单击“A-J”按钮,列表将只生成名字首字母在 A-J 之间的 div,其他字母组也类似。 到目前为止,我已经编写了以下代码:
$("#jfmfs-filter-selected-aj").click(function(event) {
event.preventDefault();
for (i = 0; i < all_friends.length ; i++)
{
var aFriend = $( all_friends[i] );
if(!(/^[a-jA-J]+$/.test(aFriend.find(".friend-name").html().charAt(0)))){
aFriend.addClass("hide-filtered");
}
}
$(".filter-link").removeClass("selected");
$(this).addClass("selected");
});
此代码工作正常,但在循环中隐藏了 div,因此需要时间。有没有一种方法可以在一行中编写上面的代码,一次性将“隐藏过滤”类添加到所有符合我的条件的 div 是这样的吗?
all_friends.not( {divs with inner html starting with letters a-j} ).addClass("hide-non-selected");
all_friends.not( /^[a-jA-J]+$/.test(all_friends.find(".friend-name").html().charAt(0)) ).addClass("hide-non-selected");
我使用 jquery 过滤器的最终解决方案(Barmar 的回答):
all_friends.filter(function() {
return(!(/^[a-fA-F]+$/.test($(this).find(".friend-name").html().charAt(0))))
}).addClass("hide-non-selected");
最佳答案
试试这个:
var AJ_regex = /^[a-jA-J]/;
$('.friend-name', aFriend).filter(function() {
return !(AJ_regex.test($(this).html()));
}).addClass("hide-filtered");
关于javascript - JQuery 检查正则表达式并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13657817/