jQuery按两个变量过滤,其中一个可能未定义

jquery filter by two variables & one of them maybe undefined

本文关键字:一个 未定义 过滤 两个 变量 jQuery      更新时间:2023-09-26

我正在编写一些jquery代码,根据类和数据属性过滤li项目。这是代码:http://pastebin.com/14eLwYWP

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

我的意思是,情况很简单,每个()仅在当前城市和当前年龄都有值时才过滤。但是当其中一个未定义时,我想显示仅由另一个变量过滤的 li-items。我不知道怎么写,但我认为主要问题就在那里:

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

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

您正在检查相等性,因此当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