在jQuery中将所有href作为数组获取

10 html jquery

我的代码看起来像这样:

<ul id="ulList">
  <li class="listClass" id="id1"><a href="http://link1">Link 1</a></li>
  <li class="listClass" id="id2"><a href="http://link2">Link 2</a></li>
  <li class="listClass" id="id3"><a href="http://link3">Link 3</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

现在我想得到以下内容:

所有链接都是一个数组

li的所有id作为数组

有谁可以帮助我吗?

air*_*tyh 19

var ids = new Array();
var hrefs = new Array();
$('#ulList li').each(function(){
  ids.push($(this).attr('id'));
  hrefs.push($(this).find('a').attr('href'));
})


Gri*_*air 15

我知道这是旧的,但是因为我喜欢jQuery允许你写的oneliners,我想我会添加它:

var allLinks = $('#ulList a').map(function(i,el) { return $(el).attr('href'); }).get();
var allIds = $('#ulList li').map(function(i,el) { return $(el).attr('id'); }).get();
Run Code Online (Sandbox Code Playgroud)

  • +1但是`allLinks`和`allIds`是类似jQuery数组的对象,它们不是真正的javascript数组.要返回真正的javascript数组,需要`allLinks = $ .makeArray(allLinks);`和`allIds = $ .makeArray(allIds);` (3认同)

Ven*_* D. 6

偶然发现了这个问题并提出了一个更可重复的答案:

$.fn.collect = function(fn) {
    var values = [];

    if (typeof fn == 'string') {
        var prop = fn;
        fn = function() { return this.attr(prop); };
    }

    $(this).each(function() {
        var val = fn.call($(this));
        values.push(val);
    });
    return values;
};

var ids = $('#ulList li').collect('id');
var links = $('#ulList a').collect('href');
Run Code Online (Sandbox Code Playgroud)

您还可以将函数传递给collect,如下所示:

var widths = $('#ulList li').collect(function() {
    return this.width();
});
Run Code Online (Sandbox Code Playgroud)


nic*_*ckf 4

这应该有效。

var ids = [],
    hrefs = []
;   
$('#ulList')
    .find('a[href]')  // only target <a>s which have a href attribute
        .each(function() {
            hrefs.push(this.href);
        })
    .end()
    .find('li[id]')   // only target <li>s which have an id attribute
        .each(function() {
            ids.push(this.id);
        })
;

// ids = ['id1', 'id2', 'id3']
// hrefs = ['http://link1', 'http://link2', 'http://link3']
Run Code Online (Sandbox Code Playgroud)