Turn array of jQuery elements into jQuery wrapped set of elements

前端 未结 11 1068
长发绾君心
长发绾君心 2021-02-01 12:39

Is there any elegant way of turning [$(div), $(span), $(li)] into $(div, span, li)?

What I need is a jQuery-wrapped set of elements instead of

11条回答
  •  梦谈多话
    2021-02-01 13:22

    If what you really mean is how to convert:

    [$(a), $(b), $(c)]
    

    into the result of:

    $(a, b, c)
    

    then you can use the add function to add each jQuery object to another jQuery object:

    var x = $();  // empty jQuery object
    $.each([$(a), $(b), $(c)], function(i, o) {x = x.add(o)});
    

    At this point, x will contain a combined jQuery object that is the combination of the previous a, b and c jQuery objects in the array.

    I couldn't find any way to do it without the each() loop. The add() function accepts an array of DOM elements as an argument, but (at least according to the documentation), not an array of jQuery objects.


    Or, you could convert each jQuery object to a DOM element, which would likely be a little more efficient because it only makes one new jQuery object at the end:

    $([$(".a"), $(".b"), $(".c")].map(function(o) { return o.get() }));
    

提交回复
热议问题