jquery过滤器由两个变量&其中一个可能未定义

时间:2013-10-13 17:55:52

标签: javascript jquery conditional filtering each

我正在编写一些jquery代码来过滤基于class&的li项目数据属性。 以下是代码:http://pastebin.com/14eLwYWP

问题是,当其中一个变量未定义时(当用户第二次单击以禁用过滤器时会发生这种情况),它不会显示任何内容。我想知道是否有任何其他解决方案,而不是为每个案例编写代码。

我的意思是,情况很简单,每个()只有当currentCity和currentAge都有值时才会过滤。但是当其中一个未定义时,我想显示仅由另一个变量过滤的li项。我不知道如何写它,但我认为主要的问题是:

$('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();
}
});

但必须有更优雅的方式来做到这一点......

1 个答案:

答案 0 :(得分:1)

您正在检查是否相等,因此当currentAge未定义时,您的过滤器会中断,因为没有元素的年龄只有"post_"且没有年龄值。 (如您所知)所以如果您使用indexOf来检查字符串是否包含短语"post_"+currentAge,那么它将不会中断,因为所有年龄属性都以"post_"开头。 indexOf函数将返回字符串中子字符串出现位置的索引,如果找不到则返回-1。 currentCity"tag-"的想法是一样的,但我们需要一个字符串来进行比较,因此我只需要使用hasClass代替.attr('class')

function globalFilter(currentCity, currentAge) {
    $('ul.the_loop').children('li').each(function () {
            if ($(this).data('age').indexOf('post_' + currentAge) > -1 && $(this).attr('class').indexOf("tag-" + currentCity) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        }

编辑:如果您要动态更改元素类,可能需要使用.prop('class')代替.attr

相关问题