将 jQuery 元素数组转换为 jQuery 包裹的元素集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6867184/
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
Turn array of jQuery elements into jQuery wrapped set of elements
提问by Scott Greenfield
Is there any elegant way of turning [$(div), $(span), $(li)]
into $(div, span, li)
?
是否有转向的任何优雅的方式[$(div), $(span), $(li)]
进入$(div, span, li)
?
What I need is a jQuery-wrapped set of elements instead of an array of jQuery elements. I would like to do this in as few lines of code as possible, and with minimal (if any) looping.
我需要的是一组 jQuery 包装的元素,而不是一组 jQuery 元素。我想用尽可能少的代码行来做到这一点,并且循环最少(如果有的话)。
Edit:For those of you confused by this question, this code is copied and pasted from firebug using console.log on an array of elements that have already been selected.
编辑:对于那些对这个问题感到困惑的人,此代码是使用 console.log 从 firebug 复制并粘贴到已经选择的元素数组上。
采纳答案by Brock Adams
jQuery's map()
functionis perfect for reshaping arrays and/or jQuery collections.
jQuery 的map()
函数非常适合重塑数组和/或 jQuery 集合。
So, givenan array set like so:
因此,给定一个数组集,如下所示:
var arrayOfJQ_Objects = [$("div"), $("span"), $("li")];
This one line of code is all you need (See it in action at jsFiddle):
这一行代码就是你所需要的(在 jsFiddle 上查看它的实际效果):
$(arrayOfJQ_Objects).map (function () {return this.toArray(); } );
Resulting in this console display in Firebug:
导致此控制台在 Firebug 中显示:
jQuery(div, span, li)
Reference, also, jQuery's .toArray()
function.
回答by jfriend00
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:
然后您可以使用 add 函数将每个 jQuery 对象添加到另一个 jQuery 对象:
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.
此时,x 将包含一个组合的 jQuery 对象,该对象是数组中前一个 a、b 和 c jQuery 对象的组合。
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.
如果没有each()
循环,我找不到任何方法来做到这一点。该add()
函数接受一个 DOM 元素数组作为参数,但(至少根据文档),而不是一个 jQuery 对象数组。
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:
或者,您可以将每个 jQuery 对象转换为一个 DOM 元素,这可能会更高效一点,因为它最后只生成一个新的 jQuery 对象:
$([$(".a"), $(".b"), $(".c")].map(function(o) { return o.get() }));
回答by jfriend00
A bit more concise than the accepted answer, one can use the $.fn.toArray
as the argument passed to $.fn.map
:
比接受的答案更简洁一点,可以将$.fn.toArray
用作传递给 的参数$.fn.map
:
var list = [$('<a>'), $('<b>'), $('<i>')];
$(list).map($.fn.toArray);
Or perhaps (this is really inferior, but only has one function call in your code):
或者(这真的很差,但你的代码中只有一个函数调用):
$.fn.map.call(list, $.fn.toArray);
回答by Guffa
You can use the add
method to copy the elements in a jQuery object to another. This will copy all elements from each of the jQuery objects in the array source
into the jQuery object items
:
您可以使用该add
方法将 jQuery 对象中的元素复制到另一个对象。这会将数组中每个 jQuery 对象的所有元素复制source
到 jQuery 对象中items
:
// Create an empty jQuery object
var items = $([]);
// Add the elements from each jQuery object to it
$.each(source, function(){ items = items.add(this); });
(Prior to version 1.3.2 the add
method doesn't support adding a jQuery object, so you would need to use items.add(this.get());
instead.)
(在 1.3.2 版本之前,该add
方法不支持添加 jQuery 对象,因此您需要items.add(this.get());
改用。)
回答by Daniel
Say you have an array of jQuery elements:
假设你有一个 jQuery 元素数组:
let elementList = [$("selector1"), $("selector2"), $("selector3"), ...];
You can simply use the jQuery function ($()
) directly on the array which will return a jQuery set:
您可以$()
直接在将返回 jQuery 集的数组上直接使用 jQuery 函数 ( ):
let jQuerySetOfElements = $(elementList);
回答by kayz1
To add single element:
添加单个元素:
var $previousElements = $();
$previousElements.add($element);
to convert array to jQuery set of elements:
将数组转换为 jQuery 元素集:
var myjQueryElementArray = [$element1, $element2, $elementN];
$(myjQueryElementArray ).map (function () {return this.toArray(); } );
to add array of elements to existing elements:
将元素数组添加到现有元素:
var $previousElements = $(),
myjQueryElementArray = [$element1, $element2, $elementN];
$previousElements.add($(myjQueryElementArray).map (function () {return this.toArray(); } ));
回答by alex
回答by fncomp
Edit: I thought jQuery supported all Array
methods, but nay, so here's a working version of my initial solution, albeit it's a bit odd since I am sticking to the same methods:
编辑:我认为 jQuery 支持所有Array
方法,但不,所以这是我初始解决方案的工作版本,尽管它有点奇怪,因为我坚持使用相同的方法:
var set; // The array of jQuery objects,
// but make sure it's an Array.
var output = set.pop();
$.each(set, function (_, item) {
return [].push.call(output, [].pop.call(item));
});
回答by meo
you could do something like this:
你可以做这样的事情:
var $temp = $();
$.each([$("li"), $("li"), $("li")], function(){
$temp.push(this[0]);
})
$temp all your elements in one jQuery selector
$temp 将所有元素放在一个 jQuery 选择器中
But i am curious what brings you to this situation having an array of different jQuery elements. You know that you can select different elements using a comma? like $("li, ul > li:eq(0), div")
但我很好奇是什么让您遇到这种具有不同 jQuery 元素数组的情况。您知道可以使用逗号选择不同的元素吗?喜欢$("li, ul > li:eq(0), div")
editas Guffa pointed out, this only adds the first element of each section. .add()
is a better choice then .push()
here.
正如 Guffa 指出的那样编辑,这只会添加每个部分的第一个元素。.add()
是比.push()
这里更好的选择。
回答by Teocci
I have a similar problem long time ago. I have a huge form and I need to get every input
. So, my idea was take each input
as jQuery object and turn it into jQuery wrapped set of elements. How can I do that? Well this is the solution for your question.
很久以前我有一个类似的问题。我有一个巨大的表格,我需要得到每个input
. 所以,我的想法是将每个input
作为 jQuery 对象并将其转换为 jQuery 包装的元素集。我怎样才能做到这一点?嗯,这是您问题的解决方案。
- First you need to create an empty array as a jQuery object like this:
let fields = $([]);
. - Now, use a string containing a selector expression to get the elements that you need in this example:
'form#details :input'
as jQuery Objects. - Then use
.each
method to extract the information that you need, and add the jQuery object to the jQuery set wrapper:fields = fields.add(input);
- 首先,你需要创建一个空的数组作为一个jQuery对象是这样的:
let fields = $([]);
。 - 现在,使用包含选择器表达式的字符串来获取本示例中所需的元素:
'form#details :input'
作为 jQuery 对象。 - 然后使用
.each
方法提取您需要的信息,并将 jQuery 对象添加到 jQuery 集包装器中:fields = fields.add(input);
How do you apply to this question?
你如何申请这个问题?
If you have a list of elements let elements = [$('#gw_id'), $('#erv_id'), $('#name')];
you can replace $('form#details :input')
with elements
;
如果你有一个元素列表,let elements = [$('#gw_id'), $('#erv_id'), $('#name')];
你可以$('form#details :input')
用elements
;
Another, alternative is to use .reduce
vanilla js. in this let set = $(elements.reduce((acc, cur) => {return acc.concat(cur.get())}, []));
snippet we use the array of elements
and apply reduce
reduce has 4 parameters but we can use the first two that are accumulator
as acc
and currentValue
as cur
also we use the Arrow function (=>
) to reduce the callback. In this callback we concatenate each current value in a new array. Finally, the return array is wrapped into a jQuery object $()
. You can replace elements
with $('form#details :input')
also.
另一种选择是使用.reduce
vanilla js。在这个let set = $(elements.reduce((acc, cur) => {return acc.concat(cur.get())}, []));
片段中,我们使用数组 ofelements
和 apply reduce
reduce 有 4 个参数,但我们可以使用前两个accumulator
asacc
和currentValue
ascur
也使用箭头函数 ( =>
) 来减少回调。在这个回调中,我们将每个当前值连接到一个新数组中。最后,返回数组被包装成一个 jQuery 对象$()
。您也可以替换elements
为$('form#details :input')
。
let fields = $([]);
let elements = [$('#gw_id'), $('#erv_id'), $('#name')];
$(function() {
console.log('List of fields: ');
$('form#details :input').each((index, value) => {
let input = $(value);
let id = input.attr('id');
let type = input.attr('type');
fields = fields.add(input);
if (id && type == 'text') {
console.log('Input: ' + id + ' | Text: ' + type);
}
});
fields.addClass('ui-state-error');
let set = $(elements.reduce((acc, cur) => {
return acc.concat(cur.get())
}, []));
console.log('Set list: ');
set.each((index, value) => {
let input = $(value);
let id = input.attr('id');
let type = input.attr('type');
console.log('Input: ' + id + ' | Text: ' + type);
});
});
.ui-state-error {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="details">
<fieldset>
<p>
<label for="gw_id">GW Id</label>
<input type="text" name="gw_id" id="gw_id" value="" class="text ui-widget-content ui-corner-all">
</p>
<p>
<label for="erv_id">ERV Id</label>
<input type="text" name="erv_id" id="erv_id" value="" class="text ui-widget-content ui-corner-all">
</p>
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" class="text ui-widget-content ui-corner-all">
</p>
<p>
<label for="description">Description</label>
<input type="text" name="description" id="description" value="" class="text ui-widget-content ui-corner-all">
</p>
<input type="hidden" name="no" id="no" value="23" disabled readonly>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>