2012-12-01 30 views
3

在我的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"); 
+0

貌似[這裏] [1]的那種東西你正在尋找.. [1]:http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions –

+0

@AidanEwen jQuery正則表達式選擇器只能應用於屬性,而不能應用於文本。 – Barmar

回答

2

試試這個:

var AJ_regex = /^[a-jA-J]/; 
$('.friend-name', aFriend).filter(function() { 
    return !(AJ_regex.test($(this).html())); 
}).addClass("hide-filtered"); 
+0

不錯 - 我喜歡它。 –

+0

謝謝我用我使用的最終解決方案更新了我的問題。 –

+0

你可以做的最簡單和最大的效率節省是在循環之外創建正則表達式('.filter()'實際上是一個循環)。 –

0

看一看這個jquery filter by James Padolsey。看起來你可以用它來做你想要的事情。

爲了您的目的,看起來是這樣的 -

$('div.friend-name').filter('div:regex(innerHTML, ^[a-jA-J])').addClass("hide-non-selected"); 

(也可能需要調整 - 我沒有測試它)。