2

我有几个对象要附加相同的事件处理程序。到目前为止,我正在这样做:

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

我知道这种方法没有问题(或者是否存在),但我想知道是否有一种速记方法可以将同一事件的同一处理程序绑定到几个不同的对象。

编辑:我的意思是,object1.bind(stuff); object2.bind(stuff); object3.bind(stuff); etc我想要的不是写,而是allObjects.bind(stuff).

4

4 回答 4

3

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

$(object1).add(object2).add(object3).bind(event,handler);
于 2012-11-08T20:13:40.537 回答
2
var myFunc = function(event){
  // do something
};

$(object).bind(event, myFunc);
$(object2).bind(event, myFunc);
$(object3).bind(event, myFunc);`
于 2012-11-08T20:13:39.463 回答
1

How about,

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

Note: Assuming the object1 is selector string.

于 2012-11-08T20:15:21.877 回答
0

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

于 2012-11-08T20:14:30.817 回答