且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一次将事件附加到多个元素

更新时间:2022-12-26 17:14:09

jQuery add method 是您想要的:


通过给定的表达式匹配更多的元素到匹配元素集




  var a = $(#a); 
var b = $(#b);
var combined = a.add(b)


Say I have the following :

var a = $("#a");
var b = $("#b");

//I want to do something as such as the following : 

$(a,b).click(function () {/* */}); // <= does not work

//instead of attaching the handler to each one separately

Obviously the above does not work because in the $ function, the second argument is the context, not another element.

So how can I attach the event to both the elements at one go ?


[Update]

peirix posted an interesting snippet in which he combines elements with the & sign; But something I noticed this :

$(a & b).click(function () { /* */ }); // <= works (event is attached to both)

$(a & b).attr("disabled", true); // <= doesn't work (nothing happens)

From what you can see above, apparently, the combination with the & sign works only when attaching events...?

The jQuery add method is what you want:

Adds more elements, matched by the given expression, to the set of matched elements

var a = $("#a");
var b = $("#b");
var combined = a.add(b)