简体   繁体   中英

Why "javascript:function()" is used in href attribute of anchor tag to call an javascript function

I have my code like this and I want to call an JavaScript function which returns an website link. Which link I want to be the value of href="" attribute. So somewhere I got the solution to do so. But there wasn't defined that why to do so. Here's my code. I want to know why to call javascript function inside href attribute href="javascript:functionname()" is to be written rather than href="functionname()".

 function hyperlinker(){ document.location.href="https://www.google.co.in"; }
 <a href="javascript:hyperlinker()"> click to get new page </a>

Having an anchor like

<a href="somefunc()">Click Me</a>

Would be interpreted as "try to navigate to the route somefunc()". So you would be sent to http://www.example.com/somefunc() . Where http: is the protocol of the current page you're on.

The javascript: , much like the http: and the mailto: and the tel: as well as any other prefix like that is the protocol to use . If you leave it off, you're leaving it up to the browser's default behavior. For relative URLs (which is what you have written), it will default to http: (Thanks Barmar)

You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

See MDN <a/> Tag href :

href

The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers:

  • Sections of a page with fragment URLs
  • Pieces of media files with media fragments
  • Telephone numbers with tel: URLs
  • Email addresses with mailto: URLs
  • While web browsers may not support other URL schemes, web sites can with registerProtocolHandler()

If your intention is to call some JavaScript function though, you shouldn't use href anyway, that's what onclick is for, or better still addEventListener() and if the anchor won't be "taking you anywhere", use a <button/> for accessibility.

Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events.

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.

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