Javascript 如何加入两个 jQuery 元素对象?.add() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3577893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:16:53  来源:igfitidea点击:

How to join two jQuery element objects? .add() isn't working

javascriptjquery

提问by Alejandro García Iglesias

I'm inside a function and I need to return a jQuery object with two elements. Inside the function I have, for example:

我在一个函数中,我需要返回一个包含两个元素的 jQuery 对象。在我拥有的函数中,例如:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    $hiddenInput.add($select);
    return $hiddenInput;
}

And outside I have:

在外面我有:

$myContainer.append(getInput());

The result expected would be:

预期的结果是:

<div id="container"><input type="hidden"><select></select></div>

But the only thing I get right now with .add() is only the input element and not the select. How can I joint those two form elements on the function return? If not possible with jQuery, then with plain JavaScript. Thanks a lot.

但是我现在使用 .add() 唯一得到的只是输入元素而不是选择。如何在函数返回时连接这两个表单元素?如果用 jQuery 不可能,那么用普通的 JavaScript。非常感谢。

回答by Tim Stone

add()creates (and returns) a new jQuery object that is the union of the original set and what you're adding to it, but you're still returning the original in your function. You seem to have wanted to do this instead:

add()创建(并返回)一个新的 jQuery 对象,它是原始集合和您添加的内容的并集,但您仍然在函数中返回原始集合。你似乎想这样做:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    return $hiddenInput.add($select);
}

回答by Jeff Rupert

You can use

您可以使用

$hiddenInput.after($select);

That will put the $selectafter the $hiddenInput, achieving what you want to get.

这将把 放在$select之后$hiddenInput,实现你想要的。

回答by Mohammad Dayyan

You can use the following:

您可以使用以下内容:

this.MergejQueryObjects = function(arrayOfJqueryObjects) {
        return $($.map(arrayOfJqueryObjects, function (el) {
            return el.get();
        }));
    }