Jquery links good practice
Have this
<a href="#">some开发者_运维知识库thing</a>
and then I handle it in Jquery code. This displays the # in browser status bar when hover. Is this a good practice for production, other alternatives? Thanks
You can use event.preventDefault()
to stop links from redirecting the page:
HTML:
<a href="http://disneyland.com/">Let's go to DisneyLand!</a>
jQuery:
$("a").click(function(e){
//jQuery passes in the event object as e
e.preventDefault();
alert("LOL, you really thought you were going?");
});
http://jsfiddle.net/TrXAs/
You don't even have to define the href attribute. Usually I will just code like this:
<a onclick="...">Link</a>
or
$('#blah').click(function(){...});
...
<a id="blah">Link</a>
Check the specifications:
http://www.w3.org/TR/2003/WD-xhtml2-20030506/mod-hypertext.html
http://www.w3.org/TR/html401/struct/links.html#edef-A
There are more I'm sure but I suppose it really depends on the doctype you're using. Anyway long story short it's not bad practice to not specify the href attribute and a validator should pass it. And yeah... # in the address bar always looks messy to me.
Hash sign appearing in the url isn't really that wrong, but the other effect you may notice is your page being scrolled to it's top after clicking a link.
To fix that, in the function which responds to your event you should use event.preventDefault()
(assuming you're catching event
parameter):
$(element).click( function(event) {
event.preventDefault();
// your code...
})
or use return false
:
$(element).click( function(event) {
// your code...
return false;
})
精彩评论