将事件处理程序绑定到多个元素 jQuery?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2793062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind an event handler to multiple elements jQuery?
提问by Alex
I've done some experimenting, but can't seem to successfully bind one event handler to multiple elements using jQuery. Here's what I've tried:
我做了一些实验,但似乎无法使用 jQuery 成功地将一个事件处理程序绑定到多个元素。这是我尝试过的:
$('selector1', 'selector2').bind('click', function() {
$('someSelector').removeClass('coolClass');
});
I've tested all my selectors, and they are all valid.
我已经测试了我所有的选择器,它们都是有效的。
Is what I'm trying to do even possible? If so, can I do it with .live()
as well?
我正在尝试做的甚至可能吗?如果是这样,我也可以这样做.live()
吗?
Thanks!
谢谢!
回答by Gabriel
To clarify let us extract the selector
string into a variable:
为了澄清,让我们将selector
字符串提取到一个变量中:
var selector = ['selector1', 'selector2'];
the above is similar to what you have written.
以上与您所写的相似。
var selector = 'selector1, selector2';
this is the correct way to use the interface. Note that it is a comma separated list of selector in a single string.
这是使用界面的正确方法。请注意,它是单个字符串中以逗号分隔的选择器列表。
$('selector1, selector2').bind(...)