I am trying to loop through all of the links on a page and add them to an array using jquery but I can't seem to get it quite right.
What I have is:
$(document).ready(function() {
var links = new Array();
var link;
for (link in $("a"))
{
links.push(link);
}
alert(links);
开发者_JAVA百科});
What I get is an array of numbers (I think one for each link on the page), and properties, events, etc. like 'selector', 'context', ... 'onmouseover' and so on.
What am I missing?
When you do $('a')
you already have a jQuery object, which is an array-like object.
If you want an actual Array
of elements, you can convert it to an Array
with $.makeArray()
.
var array = $.makeArray( $('a') );
- http://api.jquery.com/jquery.makearray/
EDIT: If you're curious about why you were getting those unexpected results in the for/in
, fire up the developer tools in your favorite browser, and log a jQuery object to the console. You'll see all those (prototyped) properties you were getting.
console.log( $('a') );
精彩评论