一次将事件附加到多个元素 [英] Attaching an event to multiple elements at one go
问题描述
var a = $(#a);
var b = $(#b);
//我想做以下一些事情:
$(a,b).click(function(){/ * * /}); //< =不工作
//而不是分别将处理程序附加到每个对象
显然上述不起作用,因为在 $
函数中,第二个参数是 context
,而不是另一个元素。
那么如何一次性地将事件附加到这两个元素?
[更新] / strong>
peirix 发布了一个有趣的片段,他将元素与&
符号相结合;但是我注意到这一点:
$(a& b).click(function(){/ * * /}) ; //< = works(事件附加到两个)
$(a& b).attr(disabled,true); //< =不工作(没有发生)
从上面可以看到,显然,与&
符号的组合仅在附加事件时有效?
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)
这篇关于一次将事件附加到多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!