href =“JavaScript”和href =“JavaScript:无效(0)”

Mic提出了一个问题:href=“javascript:” vs. href=“javascript:void(0)”,或许与您遇到的问题类似。

回答者Roko C. Buljanbalexandre给出了该问题的处理方式:

It does not cause problems but it's a trick to do the same as PreventDefault

when you're way down in the page and an anchor as:

<a href="#" onclick="fn()">click here</a>

you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);

regarding your examples

<a onclick="fn()">Does not appear as a link, because there's no href</a>

just do a {text-decoration:underline;} and you will have "link a-like"

<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>

it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.





欢迎 JavaScript 爱好者