最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind jQuery events on multiple PREDECLARED jQuery objects - Stack Overflow

programmeradmin3浏览0评论

This is how to bind multiple events on a couple jQuery selectors:

$('#selector1,.selector2').bind('event', function (e, ui) {
   // Stuff
});

But! How do you bind on predeclared jQuery objects. Example:

var jSelector1 = $('#selector1');
var jSelector2 = $('.selector2');

Because, the following doesn't work:

jSelector1,jSelector2.bind(...);

nor does:

$jSelector1,$jSelector2.bind(...);
($jSelector1,$jSelector2).bind(...);
(jSelector1,jSelector2).bind(...);

This is how to bind multiple events on a couple jQuery selectors:

$('#selector1,.selector2').bind('event', function (e, ui) {
   // Stuff
});

But! How do you bind on predeclared jQuery objects. Example:

var jSelector1 = $('#selector1');
var jSelector2 = $('.selector2');

Because, the following doesn't work:

jSelector1,jSelector2.bind(...);

nor does:

$jSelector1,$jSelector2.bind(...);
($jSelector1,$jSelector2).bind(...);
(jSelector1,jSelector2).bind(...);
Share Improve this question asked Aug 8, 2010 at 21:29 Kyle CureauKyle Cureau 19.4k23 gold badges77 silver badges104 bronze badges 1
  • and I'm not looking for jAllSelectors = $('#selector1,.selector2'); – Kyle Cureau Commented Aug 8, 2010 at 21:30
Add a ment  | 

3 Answers 3

Reset to default 9

This should work, assuming your variables hold jQuery objects

$.each([jSelector1, jSelector2], function(i,v) {

    v.bind( ... );

});

you should be able to do something like this:

var jSelector1 = $('#selector1');
var jSelector2 = $('.selector2');

$.each([jSelector1, jSelector2], function(index, value) { 
  value.bind(....); 
});

Or you can use .add().

var jSelector1 = $('#selector1'),
    jSelector2 = $('.selector2'),
    jSelector3 = $('.selector3');

jSelector1.add(jSelector2).add(jSelector3).bind('whatever', function() {
  doSomethingAwesome();
});
发布评论

评论列表(0)

  1. 暂无评论