Get all hrefs as an array in jQuery

后端 未结 8 1337
[愿得一人]
[愿得一人] 2020-12-17 20:41

My code looks like this:

  • Link 1
  • <
8条回答
  •  太阳男子
    2020-12-17 20:41

    Stumbled into this question and came up with a more reusable answer:

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

    You can also pass a function into collect like so:

    var widths = $('#ulList li').collect(function() {
        return this.width();
    });
    

提交回复
热议问题