0

我正在尝试使用 for..in 循环来选择变量中的对象,但它没有显示必要的 Li 对象。

var mUlLi = $(mUl).find('>li');      //select all li's in main Ul   
var listLength = $(mUlLi).length;
if(listLength >0 ){
    /*for(i=0;i <listLength; i++) {
        console.log(mUlLi[i]);   // works fine show the li objects  
    }*/
    for(var obj in mUlLi) {
        console.log(obj);   // show's diff objects
    }
}

我怎样才能解决这个问题 ?

4

4 回答 4

5

jQuery 有一个each()做同样的事情。

$(mUl).find('>li').each(function(){ //for each of the elements found
    console.log(this);              //in here, "this" is the DOM element <li>
});

如果您for in在 jQuery 对象上使用 a ,您还将循环浏览 jQuery 方法和属性。

但是,如果您真的想对for从该 jQuery 获得的元素进行循环(因为您不想使用each()),请直接执行:

var nodes = $(mUl).find('>li'),
    nodesLength = nodes.length,
    i, node;

for(i=0,i<nodesLength;i++){
    node = nodes[i];
}
于 2012-05-11T06:06:10.950 回答
2

您可以通过使用正确的方法来迭代数组来解决此问题 -for(.. in ..)不是用于迭代数组元素/索引,而是用于对象属性 - 这不是您想要的

只需通过以下方式使用jQuery方式.each()

mUlLi.each(function() {
    console.log(this);
});

如果出于某种原因(可能不是正当理由!)您不想要这个,您也可以使用一个好的旧for循环:

for(var i = 0; i < listLength; i++) {
    var elem = mUlLi[i];
    console.log(elem);
}
于 2012-05-11T06:05:52.443 回答
2

mUlLi(有问题的变量名)不是一个常规对象,是一个 jQuery 集合。您可以使用each().

mUlLi.each(function(){
   // `$(this)` is the current jQuery element
})
于 2012-05-11T06:07:06.543 回答
2

使用 jQuery 的 each 函数怎么样?

http://api.jquery.com/jQuery.each/

$(mUl).find('>li').each(function(i,v) {
    console.log(v);
});
于 2012-05-11T06:10:04.320 回答