jQuery 如何按类名添加点击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7685782/
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
How to add click event by class name?
提问by Bdfy
I have a example html menu:
我有一个示例 html 菜单:
<div class="mmenu">
<ul>
<li>
<div class="menu_button" id="m1" >A</div>
</li>
<li>
<div class="menu_button" id="m2" >B</div>
</li>
<li>
<div class="menu_button" id="m3" >C</div>
</ul>
</div>
Can I add click event for each element of menu by class name ?
我可以按类名为菜单的每个元素添加点击事件吗?
$('.menu_button').click(function() {
if ( id == "m1" ) ....
})
回答by Om Shankar
Optimize your code by not usinglive()
as we cannot stop propagation of live()
events
通过不使用来优化您的代码,live()
因为我们无法阻止live()
事件的传播
Use on()
(jQuery 1.7+) or delegate()
(below 1.7)
使用on()
(jQuery 1.7+) 或delegate()
(低于 1.7)
Most efficient solution for your scenario in this case would be:
在这种情况下,您的场景最有效的解决方案是:
// $('.mmenu').on("click", ".menu_button", function() { // jQuery 1.7 & up
$('.mmenu').delegate(".menu_button", "click", function() {
var id = $(this).attr('id') // or this.id
if ( id == "m1" ) {
// ..code
}
});
In this way, you have only one click eventbound to the main div $('.mmenu')
, which will also work if you add elements (new li with divs) in the future
这样,您只有一个单击事件绑定到主 div $('.mmenu')
,如果您将来添加元素(带有 div 的新 li),这也将起作用
回答by rlc
I would suggest to use the live function, instead of the .click, because the elements added on run-time will also be clickable.
我建议使用 live 函数,而不是 .click,因为在运行时添加的元素也可以点击。
$('.menu_button').live('click', function() {
var id = $(this).attr('id');
if (id == "m1") {
//do your stuff here
}
});
回答by Gabriele Petrioli
You can find the id with this.id
你可以找到id this.id
$('.menu_button').click(function() {
if ( this.id == "m1" ) ....
})
But if the code is completely different for each button, then it may not be useful to use it like that but instead bind a different handler per id.
但是如果每个按钮的代码完全不同,那么像这样使用它可能没有用,而是为每个 id 绑定不同的处理程序。
回答by James Allardice
Yes. You can bind a click
event handler to any set of DOM elements, whether they're selected by class or anything else. The syntax in your example is correct, and the event handler will be bound to each element matched by the selector.
是的。您可以将click
事件处理程序绑定到任何 DOM 元素集,无论它们是按类还是其他任何方式选择的。您示例中的语法是正确的,事件处理程序将绑定到选择器匹配的每个元素。
However, bear in mind that in your example id
will be undefined. You would have to use this.id
, as this
will refer to the element that has been clicked.
但是,请记住,在您的示例id
中将是未定义的。您必须使用this.id
,this
来引用已单击的元素。
回答by janoliver
If I understand your question correctly, try using this:
如果我正确理解您的问题,请尝试使用以下方法:
$('.menu_button').click(function() {
if ( $(this).attr('id') == "m1" ) ....
})
Btw: In this case, a switch .. case
would be far more appropriate!
顺便说一句:在这种情况下, aswitch .. case
会更合适!