How to add click event by class name?
I have a example html menu:
<div class="mmenu">
<ul>
<li>
<div class="menu_button" id="m1" >A</div>
</li>
<li>
&开发者_高级运维lt;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" ) ....
})
Optimize your code by not using live()
as we cannot stop propagation of live()
events
Use on()
(jQuery 1.7+) or delegate()
(below 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 event bound to the main div $('.mmenu')
, which will also work if you add elements (new li with divs) in the future
I would suggest to use the live function, instead of the .click, because the elements added on run-time will also be clickable.
$('.menu_button').live('click', function() {
var id = $(this).attr('id');
if (id == "m1") {
//do your stuff here
}
});
You can find the id with 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.
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.
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.
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!
精彩评论