I have a 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 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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With