Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

Merging jQuery objects

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>

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.

something like:

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

would work. Any ideas?

UPDATE:

Solved it. You can do it like this:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...