Best Practice for JS - window.open() in href or in onclick?

半城伤御伤魂 提交于 2019-12-05 18:06:06

Best practice is to use the target attribute:

<a href="http://myUrl.com" target="_blank">link-1</a>

If that doesn't suit, a click handler (ideally not assigned via attribute) would be my take.

Neither one

Make it a regular link using href and target

<a id='my-link' target="_blank" href="http://myUrlBis.com">link-2</a>

If you need to do some processing of the click with JavaScript, you can use the following

document.getElementById("my-link").onclick = function(e) {
  // Do some processing here, maybe 
  window.location = this.href
  // Return false to prevent the default action if you did redirect with script
  return false;
}

No JavaScript

<a target="_blank" href="myUrlBis.com">link</a>

With JavaScript

<a target="_blank" href="http://www.example.com" id="myLink">link</a>
<script>
    document.getElementById("myLink").onclick = function(){ //attach click event to link
        var winPop = window.open(this.href);  //`this` is reference to link, get href
        return false;  //prevent click event from clicking the link
    }
</script>

JSFiddle Example

Below code should be fine.

<a href="javascript:void(0);"  onclick="window.open(url)">

Found issue in IE (version:11) with below code

<a onclick="javascript:window.open(url)">

Problem: The parent window is getting refreshed in IE when we have javascript window.open code in href attribute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!