【问题标题】:jquery filter by two variables & one of them maybe undefinedjquery 通过两个变量过滤,其中一个变量可能未定义
【发布时间】: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


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多