Javascript JS 的最佳实践-href 或 onclick 中的 window.open()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11000967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best Practice for JS - window.open() in href or in onclick?
提问by 4wk_
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.
这个比那个好吗 ?或者更兼容?谢谢。
回答by T.J. Crowder
Best practice is to use the target
attribute:
最好的做法是使用的target
属性:
<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.
如果这不适合,我会选择一个click
处理程序(最好不通过属性分配)。
回答by Juan Mendes
Neither one
没有一个
Make it a regular link using href
and target
使用href
和使其成为常规链接 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
如果你需要用 JavaScript 对点击做一些处理,可以使用下面的
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;
}
回答by epascarello
No JavaScript
没有 JavaScript
<a target="_blank" href="myUrlBis.com">link</a>
With JavaScript
使用 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>
回答by Firos Shamsudeen
Below code should be fine.
下面的代码应该没问题。
<a href="javascript:void(0);" onclick="window.open(url)">
Found issue in IE (version:11) with below code
在 IE(版本:11)中发现问题,代码如下
<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.
问题:当我们在 href 属性中有 javascript window.open 代码时,IE 中的父窗口正在刷新。