简体   繁体   English

在新标签页或窗口中打开时,Javascript链接无效

[英]Javascript link does not work when open in new tab or window

I have some link like this 我有这样的链接

<a href="#" onclick=aFunction(this)>link</a>

Where "aFunction" opens a link in the current window. “aFunction”在当前窗口中打开链接的位置。

When this link is clicked, it is ok and opens the link, but if it is clicked as "open in new tab" or "open in new window", it does not work. 单击此链接时,可以打开链接,但如果单击“在新选项卡中打开”或“在新窗口中打开”,则无效。

aFunction code is something like this: aFunction代码是这样的:

aFunction(object)
{
   object.href = "www.mypage.com"
}

Using the context menu for "open in new X" does not trigger the click event. 使用“在新X中打开”的上下文菜单不会触发click事件。 If your code is there simply to set the new window's address, then you'd be far better off doing 如果你的代码只是设置新窗口的地址,那么你做得好得多

<a href="http://www.mypage.com" target="_new">link</a>

instead. 代替。 It won't validate, but it'll degrade better. 它不会验证,但它会更好地降级。

Why would you do something like this instead of just putting the url in the href parameter? 你为什么要做这样的事情,而不是把url放在href参数中? You can still do other stuff on the click event if you want by adding a click handler even if you use the href attribute properly. 如果您想要添加单击处理程序,即使正确使用href属性,您仍然可以在click事件上执行其他操作。

<a href="http://www.mypage.com">link</a>

<script type="text/javascript">
$(function() { // using jQuery for simplicity, but other methods work, too.
   $('a').click( function() {
        // do some other stuff
   });
});
</script>

Note that by not returning false (or using preventDefault()), we allow the normal click action to take place once our javascript has run. 请注意,通过不返回false(或使用preventDefault()),我们允许在javascript运行后执行正常的单击操作。

Use this: 用这个:

<a id="mylink" href="#">link</a>

<script>
function changeUrl()
{
   if( /* some condition here */ )
      document.getElementById('mylink').href = "www.someurl.com";
   else
      document.getElementById('mylink').href = "www.someotherurl.com";
}
</script>

In this way the "Open link in a new tab" of the browser does not brake . 通过这种方式,浏览器中的“在新选项卡中打开链接”不会制动

If the condition changes when the user touches something on the page you need to call changeUrl whenever he touches something. 如果当用户触摸页面上的某些内容时条件发生变化,则无论何时触摸某个内容,都需要调用changeUrl

Please find below a function to open url in new window: 请在下面找到一个在新窗口中打开网址的功能:

function load() {
var load = window.open('http://www.domain.com','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM