合并两个jQuery对象

问题描述:

我喜欢使用一个或多个jQuery对象的返回值将它们添加到。

I like to have a return value with one or more jQuery objects to add them to a .

var f = function() {
    var a = $('<div class="a" />');
    // do someting awesome
    return a;
};

两个s的正确示例:

var f = function() {
    var ret = $('<div class="a" /><div class="b" />');
    // do something spectecular
    return ret;
};

问题是我需要在函数内部分隔这两个对象,这不是正确的代码:

The problem is that I need these two objects separated inside the function and this is not correct code:

var f = function() {
    var a = $('<div class="a" />'),
        b = $('<div class="b" />'),
        ret = a+b;
    // do something fabulous
    return ret;
}


你可以使用 jQuery .add()方法

You can use the jQuery .add() method:

return a.add(b);

来自文档:


给定一个表示一组DOM元素的jQuery对象,.add()方法从这些元素的并集和传递给方法的元素构造一个新的jQuery对象。

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.