JavaScript function in href vs. onclick

后端 未结 15 2012
栀梦
栀梦 2020-11-22 07:17

I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the hr

相关标签:
15条回答
  • 2020-11-22 08:06

    the best way to do this is with:

    <a href="#" onclick="someFunction(e)"></a>
    

    The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses

    dojo.stopEvent(event);
    

    to do so.

    0 讨论(0)
  • 2020-11-22 08:09

    Having javascript: in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).

    A better practice would be the second way, to put your javascript into the onclick attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.

    0 讨论(0)
  • 2020-11-22 08:09

    One more thing that I noticed when using "href" with javascript:

    The script in "href" attribute won't be executed if the time difference between 2 clicks was quite short.

    For example, try to run following example and double click (fast!) on each link. The first link will be executed only once. The second link will be executed twice.

    <script>
    function myFunc() {
        var s = 0;
        for (var i=0; i<100000; i++) {
            s+=i;
        }
        console.log(s);
    }
    </script>
    <a href="javascript:myFunc()">href</a>
    <a href="#" onclick="javascript:myFunc()">onclick</a>
    

    Reproduced in Chrome (double click) and IE11 (with triple click). In Chrome if you click fast enough you can make 10 clicks and have only 1 function execution.

    Firefox works ok.

    0 讨论(0)
提交回复
热议问题