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

爷,独闯天下 提交于 2019-12-22 08:16:26

问题


Just a question about optimization, between :

<a href="#" onClick="javascript:window.open('myUrl.com');">link-1</a>

and :

<a href="javascript:window.open('myUrlBis.com');">link-2</a>

Is one better than the other ? Or more compatible ? Thanks.


回答1:


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.




回答2:


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;
}



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/11000967/best-practice-for-js-window-open-in-href-or-in-onclick

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