使用jQuery向数组添加链接 [英] Adding links to an array with jquery

查看:104
本文介绍了使用jQuery向数组添加链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历页面上的所有链接,并使用jquery将它们添加到数组中,但是我似乎不太正确.

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.

我所拥有的是:

$(document).ready(function() {

var links = new Array();
var link;

for (link in $("a"))
{
links.push(link);
}

alert(links);

});

我得到的是一个数字数组(我认为页面上的每个链接一个),以及属性,事件等,例如选择器",上下文",..."onmouseover"等等.

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.

我想念什么?

推荐答案

执行$('a')时,您已经有一个jQuery对象,它是一个类似于数组的对象.

When you do $('a') you already have a jQuery object, which is an array-like object.

如果需要实际的Array元素,则可以使用$.makeArray()将其转换为Array.

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/
    • http://api.jquery.com/jquery.makearray/
    • 编辑:如果您对为什么在for/in中得到那些意外结果感到好奇,请在您喜欢的浏览器中启动开发人员工具,并将jQuery对象记录到控制台中.您将看到所获得的所有那些(原型)属性.

      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') );
      

      这篇关于使用jQuery向数组添加链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆