简体   繁体   中英

JQuery attach same event to 2 objects

I have several objects to whom I would like to attach the same event handler. So far, I'm doing this:

$(object).bind(event, function(event) {
    // Code
});
$(object2).bind(event, function(event) {
    // Same code
});
$(object3).bind(event, function(event) {
    // Same code again
});

I know there's nothing wrong with this approach (or is there), but I'm wondering if there's a shorthand method for binding the same handler for the same event to several different objects.

EDIT: what I mean is, instead of writing object1.bind(stuff); object2.bind(stuff); object3.bind(stuff); etc object1.bind(stuff); object2.bind(stuff); object3.bind(stuff); etc object1.bind(stuff); object2.bind(stuff); object3.bind(stuff); etc I want something like allObjects.bind(stuff) .

您可以使用.add方法一次选择它们:

$(object1).add(object2).add(object3).bind(event,handler);
var myFunc = function(event){
  // do something
};

$(object).bind(event, myFunc);
$(object2).bind(event, myFunc);
$(object3).bind(event, myFunc);`

How about,

$('selector1, selector2, selector3').bind(event, function(event) {
    // Same code again
});

Note: Assuming the object1 is selector string.

Just define an variable containing the function an then bass the object to each bind. Like this:

var fn = function(event) {};
$(object).bind(fn);
$(object2).bind(fn);
$(object3).bind(fn);

Apendix: you can store your objecs in an array an iterate over them:

$([object, object2, object3]).each(function(){
    this.bind(fn);
});

However I don't think this is a good coding style....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM