In Javascript, how to prevent Default for a child from inside the parent event handler

Suppose I have this HTML:

<div> <a href="http://google.com">Google</a> </div> 

And I have such an event handler (suppose I have jQuery):

 $('div').on('click', function(ev) { // ... }); 

Is it possible, from within this event handler, to prevent the default action of the <a> link? Or is it too late? (In other words, I need to attach the event to <a> or lower to prevent the default link from working, or I can stop it in the above handler).

As said above, I have jQuery if this requires its solution.

+4
source share
2 answers

This will definitely work:

 $('div').on('click', "a", function(e) { e.preventDefault(); }); 

Here's the script: http://jsfiddle.net/xvKNC/1/

Hold on this seems to work fine for me in Chrome

 // prevent default on every click in the div $('div').on('click', function(ev) { ev.preventDefault(); }); 

See the updated script: http://jsfiddle.net/xvKNC/2/

+8
source

It seems to work:

 $('div').on('click', function(ev) { ev.stopImmediatePropagation(); ev.preventDefault(); }); 

JSFiddle: http://jsfiddle.net/3yFfC/

+4
source

Source: https://habr.com/ru/post/1412082/


All Articles