为什么地图没有返回正确的结果

时间:2012-02-21 21:39:25

标签: jquery

我正在尝试循环遍历dom元素数组,并且只有在匹配特定条件时才返回dom元素。在下面的情况下,如果id属性等于值“0”并且它具有带有类名记录的子元素。 我已经尝试了下面的代码,但它总是返回元素0,即使它没有带有类记录的子代。

var el = shows.map(function(index, element) {
    if (this.id == "0" && $(element).children('.record')) return this;
});

3 个答案:

答案 0 :(得分:0)

在您不希望映射数组中的项目的情况下,尝试特定地返回null。

var el = shows.map(function(index, element) {
    if (this.id == "0" && $(element).children('.record')) 
        return this;
    else
       return null;
});

答案 1 :(得分:0)

$(element).children('.record')更改为$(element).children('.record').length

如果jQuery找不到任何元素,它会返回一个空数组,JavaScript将其转换为true

答案 2 :(得分:0)

尝试使用jQuery

$(element).filter(function(key, value){
   return $(value).children('.record').length>0;
});