1

我正在编写一些 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();
    }
});

希望你们能帮助我;)

祝你有美好的一天和欢呼!

编辑:因为这个代码,虽然很愚蠢,但可以工作......</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();
}
});

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

4

1 回答 1

1

您正在检查是否相等,因此当currentAge未定义时,您的过滤器会中断,因为没有元素的年龄只是"post_"其后没有年龄值。(如您所知)因此,如果您使用 indexOf 来检查字符串是否包含该短语,"post_"+currentAge那么它不会中断,因为所有年龄属性都以"post_". indexOf 函数将返回子字符串在字符串中出现的位置的索引,如果找不到,则返回 -1。currentCityand的想法是相同的"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

于 2013-10-13T20:25:04.880 回答