简体   繁体   中英

When is “javascript: …” needed?

Is the javascript: prefix really needed? I know you should aim for unobtrusive JavaScript but under what circumstances would something break if it is not there?

javascript: is a URI scheme.

It is needed to create a URI that runs Javascript, either in an href="" attribute or in the browser address bar.
There is never a situation in which javascript: is optional.

Best practices indicate that javascript: URIs should be avoided where possible in favor of click handlers, so its use is frowned upon.

However, there are cases where there is no alternative. For example, bookmarklets can only be created by using javascript: .

They're "needed" if you are encoding Javascript code into an URI, for example in the href property of an <a> tag.

They're bad practice, though.

If you put JavaScript code into the href attribute of an a , or other attribute which takes a URL, then it's required for the browser to detect that it is JS. It's not necessary (and may not even work) if you use it with onclick or other attributes that already expect JS code.

That "prefix" is used only in the href attribute of an html anchor (). It is never actually needed, since you could as well define a click event handler.

It is needed even in onclick situations if you also have a VBS routine on the same page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM