What is the best way to execute a function when user clicks on a link?
From my experience I know three different ways to execute a JavaScript function when a user clicks on a link
Use the
onclick
attribute on the link<a href="#开发者_运维问答" onclick="myfunction();return false;">click me</a>
Use the
href
on the link<a href="javascript:myfunction();">click me</a>
Don't touch the link, do everything in js
<a href="#">click me</a>
(in the JavaScript we will stop the default event, and call the function)
Which one is better? What are the advantages and disadvantages?
EDIT deleted the "javascript:" on onclick
Unobtrusive Javascript (your third example) with graceful degredation is the best choice.
It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.
<a href="http://www.mywebsite.com/javascriptdisabled.html" onclick="myfunction(); return false;">click me</a>
None of the above. Use the click
event (assigned either as an attribute or via script if you prefer) and have a real URL as a fallback:
<a href="realpage.html" onclick="myfunction(); return false;">click me</a>
or HTML:
<a href="realpage.html" id="myLink">click me</a>
Script:
document.getElementById("myLink").onclick = function() {
myfunction();
return false;
};
Also, don't prefix code in event handler attributes with javascript:
. It's incorrect and only doesn't throw an error by coincidence (which is that in JavaScript, javascript:
creates a label called javascript
).
Or alternatively, use jQuery
$(function() {
$('[id$=myLinkID]').click(function(e) {
myFunction();
});
});
精彩评论