3

私の HTML には、それぞれが内部に名前を持つ多数の div があります。アルファベットのフィルターを実装する必要があります。ユーザーがボタン「AJ」をクリックすると、リストは、名前の最初の文字が AJ の間にある 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 を非表示にするため、時間がかかります。上記のコードを1行で記述して、基準を満たすすべてのdivに「hide-filtered」クラスを一度に追加する方法はありますか?

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");
4

2 に答える 2

2

これを試して:

var AJ_regex = /^[a-jA-J]/;
$('.friend-name', aFriend).filter(function() {
    return !(AJ_regex.test($(this).html()));
}).addClass("hide-filtered");
于 2012-12-01T09:11:51.720 に答える
0

James Padolsey によるこのjquery フィルターをご覧ください。これを使用して、探している種類のことを行うことができます。

あなたの目的のために、それは次のようになります-

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

(おそらく微調整が必​​要です-私はそれをテストしていません)。

于 2012-12-01T09:11:47.367 に答える