jQuery $(“.class”).click(); - multiple elements, click event once

前端 未结 18 1658
借酒劲吻你
借酒劲吻你 2020-11-29 00:01

I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple

18条回答
  •  春和景丽
    2020-11-29 00:53

    Apologies for bumping this old thread. I had the same problem right now, and I wanted to share my solution.

    $(".yourButtonClass").on('click', function(event){
        event.stopPropagation();
        event.stopImmediatePropagation();
        //(... rest of your JS code)
    });
    

    event.StopPropagation and event.StopImmediatePropagation() should do the trick.

    Having a .class selector for Event handler will result in bubbling of click event (sometimes to Parent element, sometimes to Children elements in DOM).

    event.StopPropagation() method ensures that event doesn't bubble to Parent elements, while event.StopImmediatePropagation()method ensures that event doesn't bubble to Children elements of desired class selector.

    Sources: https://api.jquery.com/event.stoppropagation/ https://api.jquery.com/event.stopimmediatepropagation/

提交回复
热议问题