在我的HTML裏面有多個div,每個div都有名字。我必須在其中實施字母過濾器。如果用戶點擊按鈕「A-J」,該列表將僅創建名稱的第一個字母在A-J之間以及其他字母組相似的div。 我已經寫了下面的一段代碼至今:JQuery與正則表達式檢查和添加類
$("#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");
貌似[這裏] [1]的那種東西你正在尋找.. [1]:http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions –
@AidanEwen jQuery正則表達式選擇器只能應用於屬性,而不能應用於文本。 – Barmar