How to join two jQuery element objects? .add() isn't working
I'm inside a function and I need to return a jQuery object with two ele开发者_Go百科ments. Inside the function I have, for example:
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() 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:
function getInput() {
$hiddenInput = $('<input type="hidden">');
//(other code)
$select = $('<select></select>');
//(other code)
return $hiddenInput.add($select);
}
You can use
$hiddenInput.after($select);
That will put the $select
after the $hiddenInput
, achieving what you want to get.
You can use the following:
this.MergejQueryObjects = function(arrayOfJqueryObjects) {
return $($.map(arrayOfJqueryObjects, function (el) {
return el.get();
}));
}
精彩评论