我尝试使用 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
}
}
我该如何解决这个问题?
最佳答案
jQuery 有一个 each()
做同样的事情。
$(mUl).find('>li').each(function(){ //for each of the elements found
console.log(this); //in here, "this" is the DOM element <li>
});
如果您在 jQuery 对象上使用 for in
,您还会循环遍历 jQuery 方法和属性。
但是,如果您确实想对从 jQuery 获取的元素执行 for
循环(因为您不想使用 each()
),然后直接执行:
var nodes = $(mUl).find('>li'),
nodesLength = nodes.length,
i, node;
for(i=0,i<nodesLength;i++){
node = nodes[i];
}
关于javascript - 使用 for..in 循环对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546213/