How to add click event by class name?

后端 未结 5 933
野性不改
野性不改 2020-12-31 20:45

I have a example html menu:

  • A
5条回答
  •  无人及你
    2020-12-31 21:18

    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

提交回复
热议问题