【发布时间】:2013-10-21 07:37:34
【问题描述】:
我正在编写一些 jquery 代码来根据类和数据属性过滤 li 项目。 这是代码:http://pastebin.com/14eLwYWP
问题是,当其中一个变量未定义时(当用户第二次单击以禁用过滤器时会发生这种情况),它不会显示任何内容。我想知道这个问题是否有其他解决方案,而不是为每个案例编写代码。
我的意思是,情况很简单,each() 仅在 currentCity 和 currentAge 都有值时过滤。但是当其中一个未定义时,我想显示仅由另一个变量过滤的项目。我不知道怎么写,但我认为主要的问题是:
$('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();
}
});
希望你们能帮助我;)
祝你有美好的一天和欢呼!
编辑:因为这个代码,虽然很愚蠢,但可以工作......
$('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();
}
});
但是必须有更优雅的方式来做到这一点......
【问题讨论】:
标签: javascript jquery conditional filtering each