开发者

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

  1. Use the onclick attribute on the link

     <a href="#开发者_运维问答" onclick="myfunction();return false;">click me</a>
    
  2. Use the href on the link

     <a href="javascript:myfunction();">click me</a>
    
  3. 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();
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜