jQuery 1.7 on() method

1.6k Views Asked by At

I have just downloaded jQuery 1.7 for a brand new project I'm starting.

After reading the the docs I see .on() now replaces .live(). Quote from the docs:

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For equivalents to older jQuery event methods, see .bind(), .delegate(), and .live().

So what I'm trying to do is quite simple. I have the following jQuery which of course uses the old method:

$('a').live('click', function(e){
    e.preventDefault(); 
});

This works just fine, by that I mean the anchors' default behaviour is prevented. If I use this:

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

The anchors' default behaviour is not prevented and when clicked it loads another page. Am I doing something blatantly wrong here or have I misunderstood .on()?

1

There are 1 best solutions below

5
On BEST ANSWER

It DOES work.

http://jsfiddle.net/RsHnn/

Are you sure you don't have any JS error on that page / you are sure you are using jQuery 1.7?

EDIT

It looks like you need to add the selector if you want it the work with dynamically added elements.

http://jsfiddle.net/RsHnn/2/