I'm trying to use $().live to enhance a website but it insists on following the href. The following is very close to the real code (a.class, span inside a).
<a class="test" href="http://google.com"><span>test</span></a>
$('a.test').live('click', function(event){
event.preventDefault();
$(this).text('clicked');
});
Testing this in jsfiddle works, but not when I use it in my project. The handler is triggered开发者_运维技巧, but the href is also followed. I've tried both return false and event.preventDefault() with the same result.
Try as I might I can't find anything that would stop this working in my site.
So my question is, should this actually ever work? If so is there anything that would cause it not to?
It turns out the problem was jQuery mobile. Even with $.mobile.ajaxEnabled = false
it captures click events and sets location.href = $this.attr( "href" );
unless the element has data-ajax="false"
. I may bind my event before loading jQmobile, or even unbind it's event since I'm not using their nav.
Offending code in jQuery mobile
Don't even put the href tag in there you don't need it if you aren't using it as a link.
If you want to control when the link is followed you can remove the href from the link and put window.location in the live() function so you have control when the link is actually followed.
I assume that the jquery code is inside a
$(document).ready(function(){
// your code here?
});
Here is an updated jsFiddle. http://jsfiddle.net/vG5gW/1/
Right now jsFiddle is probably working because the DOM for the link is loaded before the script by luck.
Bob
I see what you are saying, what you COULD do is give the link an id and have jquery replace the value of href. If javascript is not available then the link will remain intact, if not then the link href will be changed to # or whatever you'd like it to.
精彩评论