我正在编写一些 jquery 代码来根据类和数据属性过滤 li 项目。 这是代码:http://pastebin.com/14eLwYWP
问题是,当其中一个变量未定义时(当用户第二次单击禁用过滤器时会发生这种情况),它不会显示任何内容。我想知道这个问题是否还有其他解决方案,而不是为每种情况编写代码。
我的意思是,情况很简单,each() 仅当 currentCity 和 currentAge 都有值时进行过滤。但是,当其中一个未定义时,我想显示仅由另一个变量过滤的 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
那么它不会中断,因为所有年龄属性都以 "开头帖子_”
。 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
关于javascript - jquery 通过两个变量进行过滤,其中之一可能未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348362/