How to add click event by class name?

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

I have a example html menu:

  • A
    相关标签:
5条回答
  • 2020-12-31 21:03

    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
      }
    });
    
    0 讨论(0)
  • 2020-12-31 21:06

    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.

    0 讨论(0)
  • 2020-12-31 21:12

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-31 21:25

    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!

    0 讨论(0)
提交回复
热议问题