• Prevent bubling event not working in jquery

    I have a DOM like this

    <div class="modal"> <li> <div id="block1"></div> <div id="block2"> <div class="btn-wrap"> <button>cancel</button> <button>save</button> </div> </div> </li> 

    I have a click event attached to li, and when I click the block2 button, this event happened. How to prevent this?

    I tried using on () but it does not work.

     $('.btn-wrap').on('click','button:first-child',function(e){ e.preventDefault(); alert('test'); }); 
    +6
    source share
    2 answers

    You should use stopPropagation to prevent event bubbles:

     $('.btn-wrap').on('click','button:first-child',function(e){ e.stopPropagation(); alert('test'); }); 
    +3
    source

    Add event.stopPropagation () to your handler

     $('.btn-wrap').on('click', 'button:first-child', function(e) { e.preventDefault(); e.stopPropagation(); alert('test'); }); 
    +1
    source

    All Articles