合并 jQuery 对象

是否有可能将多个 jQueryDOM 对象合并到一个数组中,并对所有数组调用 jQuery 方法?

联系方式:

<button>one</button>
<h3>two</h3>


<script>


var btn = $('button');
var h3 = $('h3');


$([btn,h3]).hide();


</script>

这不管用。我知道我可以在这里使用‘ Button,h3’选择器,但是在某些情况下,我已经有了几个 jQuery DOM 元素,我需要合并它们,这样我就可以在所有元素上调用 jQuery 原型。

比如:

$.merge([btn,h3]).hide();

会有用的,有什么想法吗?

更新:

解决了,你可以这样做:

$.fn.add.call(btn,h3);

我将接受 add()的建议,因为它为我指明了正确的方向。

36247 次浏览
$(btn).add(h3).hide();

但是不确定它是否有效,因为 add 的 文件没有提到将 jQuery 对象作为一个参数,而只是提到了一个元素列表,所以如果这个不起作用,应该这样做:

$(btn).add(h3.get()).hide();

.add() 完全符合你的要求。

h3.add(btn).hide();

如果你想让它对你自己更方便一点,像你的问题中的“合并”功能,这可以很容易地添加:

$.merge = function(objs) {
var ret = objs.shift();
while (objs.length) {
ret = ret.add(objs.shift());
}
return ret;
};


$.merge([h3, btn]).hide()

$.map可以压平数组:

function merge(array_of_jquery_objects) {
return $($.map(array_of_jquery_objects, function(el) {
return el.get();
}));
}

用这个。

<script>


var btn = $('button')[0];
var h3 = $('h3')[0];


$([btn,h3]).hide();


</script>

获取一些 jQuery 对象:

var x = $('script'),
y = $('b'),
z = $('body');

创建一个包含所有其他对象的新 jQuery 对象:

$( $.map([x,y,z], a => [...a]) )

演示: (打开浏览器控制台)

var x = $('script'),
y = $('b'),
z = $('body');


// step 1
// put all the jQuery objects in an Array to prepare for step 2
var step1 = [x,y,z];
console.log(step1)


// using jQuery.map and a callback, extract  the actual selector from the iterable
// array item and return it, so the result would be a simple array of DOM nodes
// http://jqapi.com/#p=jQuery.map
var step2 = $.map(step1, a => [...$.makeArray(a)])
console.log(step2);


// convert the javascript Array into jQuery Object (which contains all the nodes)
var step3 = $( step2 )
console.log(step3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<b></b>

要进一步使用 add,您可以使用 reduce作为另一种方法:

var $mySelector1 = $('.selector1');
var $mySelector2 = $('.selector2');
var $mySelector3 = $('.selector3');
var selectorArray = [$mySelector1,$mySelector2,$mySelector3];
var $combinedSelector = selectorArray.reduce(function(total, current){
return $(total).add(current)
});