Why do you see colons while calling a javascript function in html sometimes?

前端 未结 3 1872
抹茶落季
抹茶落季 2021-02-20 15:12

A lot of the time I see people calling javascript functions using colon (:).

Like onclick=\"javascript:functionname();\"

The same function works wit

相关标签:
3条回答
  • 2021-02-20 15:24

    This is not as commonly seen in onclick events as these events already execute javascript. You will may see something like the following quite a bit:

    <a href="javascript: functionname(); return false;">Link</a>
    

    The reason for such code is that by default an href attribute is trying to change the location or redirect. This tells the browser that the default href action will be javascript that is run. Otherwise, the function will not run and the page will refresh which is quite annoying.

    Page refreshing is a common issue when using javascript like this in an anchor tag since an anchor tags default action is to refresh or load another page. The return false; at the end signals that the default action (i.e. refresh or load) should not fire.

    Hope this helps.

    0 讨论(0)
  • 2021-02-20 15:34

    I believe the javascript: prefix is left over from when there were many other script types bouncing around on the web (vbScript, for example) and in order to differentiate between them in HTML you needed to provide these prefixes.

    That being said, these tags do absolutely nothing in any browser other then IE anymore, and even in IE you generally can omit them.

    Also notice that this entire question is moot since you should be binding event handlers through javascript, not in HTML.

    0 讨论(0)
  • 2021-02-20 15:35

    javascript: prefix is extremely important when you put code to anchor href attribute:

    <a href="javascript:func();">Anchor</a>
    

    Whereas in inline event attributes (like onclick, onsubmit, onmouseover, etc.) javascript: prefix is not important.

    However, you should note that both approaches given here are not good to implement and you should use alternative ways (e.g as @Paul S. stated in the comments)

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