Event.preventDefault (); not working with .on in jQuery

As of jQuery 1.7 .live deprecated and replaced with .on . However, it is hard for me to get jQuery .on to work with event.preventDefault(); . In the example below, clicking the anchor tag leads me to the linked page, rather than preventing the default browser from following the link.

 jQuery('.link-container a').on('click', function(event) { event.preventDefault(); //do something }); 

However, the same code with .live works without any hiccups.

 jQuery('.link-container a').live('click', function(event) { event.preventDefault(); //do something }); 

I am using jQuery version 1.7.1, which comes with Wordpress 3.3.1. What am I wrong here?

+4
source share
3 answers

You are not tying it correctly. .on() method works like a .delegate() when doing what you want to do. Here is an example of proper use:

 $('.link-container').on('click', 'a', function(event){ event.preventDefault(); }) 

This assumes that the .link container is on page load and not loading dynamically. You need to associate the delegate method with the closest ancestor that exists statically, and in the second argument, in this case 'a' indicate which elements the delegation method applies to.

Just using $('selector').on('click', function() { }) gives exactly the same result as using $('selector').click(function(){ })

Here is a jsfiddle example: http://jsfiddle.net/gTZXp/

+7
source

If your a elements are added dynamically, you need to use on() with a filter (as delegate() ), for example:

 jQuery('.link-container').on('click', 'a', function(event) { event.preventDefault(); //do something }); 

This suggests that .link-container not dynamic and is accessible to the DOM when the page loads.

+1
source

Try as follows: -

 var $j = jQuery.noConflict(); $j(function(){ j('.link-container').on('click', 'a', function(event) { event.preventDefault(); }); }); 
+1
source

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


All Articles