简体   繁体   中英

why do developers use href equals javascript?

why do developers use href="javascript:;"

eg:Content of the A Tag:

<a class="anchor" title="title" href="javascript:;" id="someId">...</a>

The javascript: pseudo-protocol tells the browser that what follows is JavaScript code that should be executed when the link is clicked. What follows in your example is a no-op, and so clicking the link does nothing. Typically this is used when the link isn't being used as a link but rather as a button, where the actual behavior the coder wants is specified by a click handler.

from my experience using, if people use <a href="www.google.com"> I can right click and open it on a new tab. But if it is href=javascript:openLink() I can't open it on a new tab

Good question. Its so that their link doesn't do anything. The developer is probably adding in the javascript function dynamically using Jquery's click event or something similar.

It seems to be a legacy bad habit that people have. They probably want the style of an href but then don't want the functionality of it. You can easily do this without using an href. In a way, they are saying "Here is the value for a link" and then immediately going "ignore the value for my link".

There is a good discussion here: Unobtrusive Javascript

According the the w3schools the value for an href should be a url or a script. When someone does href="javascript:;"

They are using a script that does nothing. They just do it so they can using the styling/tabbing the href offers... which, in my opinion, should be done another way like using css classes.

Also according to the w3schools the tag cannot use certain other attributes if the href is not present, but in HTML5 the tag should only be used for hyperlinks.

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