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

10

我的代码看起来像这样:

<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>

现在我想要获得以下内容:

所有链接作为一个数组

所有li的id作为一个数组

有人可以帮忙吗?

8个回答

20
变量ids和hrefs分别是数组类型。通过遍历id为ulList的ul元素下的li元素,将每个li元素的id属性值加入ids数组中,并将该li元素内a标签的href属性值加入hrefs数组中。

15
我知道这个很老了,但是因为我喜欢jQuery允许你编写的一行代码,所以我想添加它:

我知道这个很老了,但是因为我喜欢jQuery允许你编写的一行代码,所以我想添加它:

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

3
但是 allLinksallIds 是 jQuery 的类似数组对象,它们不是真正的 JavaScript 数组。要返回真正的 JavaScript 数组,需要使用 allLinks = $.makeArray(allLinks);allIds = $.makeArray(allIds); - Jose Rui Santos
1
你不需要使用 $.makeArray(),在 map() 之后你可以直接调用 .get() - Rory McCrossan

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

你也可以像这样将一个函数传递到 collect 中:
var widths = $('#ulList li').collect(function() {
    return this.width();
});

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']

1
var links = [], ids = [];
var $ul = $('#ulList');
var $lis = $ul.children('li');
var $as = $lis.children('a');

for(var count = $lis.length-1, i = count; i >= 0; i--){
    ids.push($lis[i].id);
    links.push($as[i].href);
}

1
如果您喜欢一行代码并且不想实例化一个空数组。
[]
  .slice
  .call($('#ulList a'))
  .map(el => el.getAttribute('href'))

0
我来寻找一行代码。下面是我想到的:
var hs=[]; $('a').each(function(i,a){hs.push(a.href);}); hs;

0

与Grimace提供的代码相同,但使用ES6编写

const allLinks = $('#ulList a').map((i,el) => $(el).attr('href')).get();
const allIds = $('#ulList li').map((i,el) => $(el).attr('id')).get();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接