合并jQuery对象 [英] Merging jQuery objects

查看:93
本文介绍了合并jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将多个jQuery DOM对象合并为一个数组,并在所有对象上调用jQuery方法?

Is it possible to merge several jQuery DOM objects into one array and call jQuery methods on all of them?

F.ex:

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

<script>

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

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

</script>

这不起作用.我知道我可以在这里使用按钮,h3"选择器,但在某些情况下,我已经有几个jQuery DOM元素,我需要将它们合并,以便可以在所有这些元素上调用jQuery原型.

This doesn't work. I know I can use the 'button,h3' selector here but in some cases I already have several jQuery DOM elements and I need to merge them so I can call jQuery prototypes on all of them.

类似:

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

会工作.有什么想法吗?

would work. Any ideas?

更新:

解决了.您可以这样做:

Solved it. You can do it like this:

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

我将接受add()的建议,即指向正确的方向.

I'm going to accept the add() suggestion as for pointing me in the right direction.

推荐答案

.add() 确实正是您所追求的.

.add() does exactly what you're after.

h3.add(btn).hide();

如果您想使自己更方便一些,可以使用问题中的合并"功能,可以轻松添加:

If you wanted to make it a little more convenient for yourself, with a "merge" function like in your question, this could be added easily:

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

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

这篇关于合并jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆