开发者

What does jQuery object contain?

let's say, i have this code:

<ul>
  <li><strong>list</strong> item 开发者_JS百科1 -
    one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> -
    two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

<script>
    var x = $("li");
    for (var k in x){
        alert(k + x[k]);
    }
</script>

The problem is: alert outputs too many things! Why? Why doesn't it output only li elements?? Where do li elements get stored?? How do i output only li elements to which jQuery methods usually applied??


You can use the jquery each function.

$("li").each(function(index, el){
      ..
});

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


Using a for...in construct will also iterate all properties, including all properties inherited through the prototype chain, which is why you get all the properties of the object alerted, as well as the set of matched li elements.

If you use a normal for loop (or, as others have noted, the jQuery each method), it would work:

var x = $("li");
for (var k = 0; k < x.length; k++){
    alert(k + x[k]);
}


It will alert the entire prototype chain. Use each function in jQuery(javascript) to iterate over the li elements. Moreover for in is not suggested as a right choice for iterating over objects.


An jQuery "object" does not only contain the DOMnode references. If you loop over it like that (for..in), you'll get all properties which are directly on the object and inherited via the prototype chain. You should simply use jQuerys very own .each() method to loop over it's DOMnode references:

x.each(function( index, node ) {
    console.log('Hi, I am at index ', index, ' and my reference is: ', node);
});


jQuery wraps an object around the DOM elements that match the selector, see http://api.jquery.com/jQuery/ for more details.

The contents of those alert are the functions and properties of that object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜