Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

href="javascript:" vs. href="javascript:void(0)"

Our web app is rendered totally on the browser.
The server only talks to the browser through JSON messaging.

As a result, we only need a single page for the app and mostly all the <a> tags do not have a real href pointing to other pages.

In my quest of removing unnecessary things I was wondering if I can get rid of the zillions of void(0) we have in our code, as they seem useless:

<a onclick="fn()">Does not appear as a link, because there's no href</a>
<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>

Does anybody knows if using href="javascript:" can cause a problem?
It works even on IE7...

Please don't spend your valuable time to tell me inline javascript is bad, as this is generated by a template engine :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...