クラスとデータ属性に基づいてliアイテムをフィルタリングするためのjqueryコードを書いています。コードは次のとおりです。http://pastebin.com/14eLwYWP
問題は、変数の 1 つが未定義の場合 (ユーザーがフィルターを無効にするために 2 回クリックしたときに発生)、何も表示されないことです。すべてのケースに対してコードを書くのではなく、この問題に対する他の解決策があるのではないかと思っていました。
つまり、状況は単純です。 each() は、 currentCity と currentAge の両方に値がある場合にのみフィルター処理されます。しかし、そのうちの1つが未定義の場合、別の1つの変数のみでフィルタリングされたli-itemを表示したい. 書き方がわかりませんが、主な問題はそこにあると思います。
$('ul.the_loop').children('li').each(function() {
if ($(this).data('age') == 'post_' + currentAge && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if (currentAge == undefined || currentCity == undefined) {
//don't know what to do there, both with logic and code...
} else {
$(this).hide();
}
});
皆さんが私を助けてくれることを願っています;)
良い一日をお過ごしください & 乾杯!
編集: このコードは、ばかげていますが、機能するため…</p>
$('ul.the_loop').children('li').each(function() {
if ($(this).data('age') == 'post_' + currentAge && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if (currentAge == undefined && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if ($(this).data('age') == 'post_' + currentAge && currentCity == undefined) {
$(this).show();
} else if (currentAge == undefined && currentCity == undefined) {
$(this).show();
} else {
$(this).hide();
}
});
しかし、これを行うにはもっとエレガントな方法があるはずです...