How to add jQuery objects to the jQuery composite object

前端 未结 1 1523
孤独总比滥情好
孤独总比滥情好 2021-01-18 11:41

Simply put: the jQuery object is a composite pattern. How do I add jQuery objects to it?

An example:

var e1 = $(\'#element1\');
var e2 = $(\'#element         


        
相关标签:
1条回答
  • 2021-01-18 12:34

    You can use jQuery's .add() method:

    var e1 = $('#element1');
    var e2 = $('#element2');
    
    var jq = $();
    jq = jq.add(e1).add(e2);
    jq.hide();
    

    It returns a new jQuery object instead of modifying the original, so you need to overwrite the original if you want to reuse the same variable.


    EDIT: Note that you can also use jQuery.merge(), which will modify the original, but you'll need to pass in an Array of the DOM elements instead of the jQuery objects.

    var e1 = $('#element1');
    var e2 = $('#element2');
    
    var jq = $();
    $.merge( jq, [e1[0], e2[0]] );
    jq.hide();
    ​
    
    0 讨论(0)
提交回复
热议问题