How to add click event by class name?
I have an example html menu:
<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 a click event for each menu item by class name?
$('.menu_button').click(function() { if ( id == "m1" ) .... })
Optimize your code without using live()
as we cannot stop the distribution of live()
events
Use on()
(jQuery 1.7+) or delegate()
(below 1.7)
The most effective 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 } });
This way, you only have one click event associated with the main div $('.mmenu')
, which will also work if you add elements (new li with div) in the future
Yes. You can associate a click
event handler with any set of DOM elements, regardless of whether they are selected by a class or anything else. The syntax in your example is correct, and the event handler will be bound to each element corresponding to the selector.
However, remember that in your example id
will be undefined. You will need to use this.id
since this
will refer to the element that was clicked.