在新窗口中打开链接后如何使用JavaScript更改href属性? [英] How to change href attribute using JavaScript after opening the link in a new window?

查看:125
本文介绍了在新窗口中打开链接后如何使用JavaScript更改href属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个链接

 < a href =http://google.comid = mylinkonclick =changeLink();目标= _空白 >谷歌< / A> 

目标是跟随此链接(在新标签中打开)并更改其属性前一个标签)。我的意思是我们在一个新标签中打开google.com,如果我们回头看链接,它会刷新。



我试过这个js代码

  function changeLink(){
document.getElementById(mylink)。href =http://facebook.com;
document.getElementById(mylink)。innerHTML =facebook;
}

但它也改变了新开标签的目标。



是否可以修复它?

解决方法

你的 onclick 在href之前触发,所以在页面打开之前它会改变,你需要让该函数处理窗口打开,如下所示:

  function changeLink(){
var link = document.getElementById(mylink);

window.open(
link.href,
'_blank'
);

link.innerHTML =facebook;
link.setAttribute('href',http://facebook.com);

返回false;
}


I have a link on my page

<a href="http://google.com" id="mylink" onclick="changeLink();" target="_blank">google</a>

And the goal is to follow this link (opening in a new tab) and change its attributes (on previous tab). I mean we open google.com in a new tab and if we look back on the link, it's refreshed.

I've tried this js code

function changeLink(){
    document.getElementById("mylink").href = "http://facebook.com";
    document.getElementById("mylink").innerHTML = "facebook";
    }

But it also changes the target of new opening tab. Instead of opening google it opens facebook in my example.

Is it possible to fix it?

解决方案

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

function changeLink() {
    var link = document.getElementById("mylink");

    window.open(
      link.href,
      '_blank'
    );

    link.innerHTML = "facebook";,
    link.setAttribute('href', "http://facebook.com");

    return false;
}

这篇关于在新窗口中打开链接后如何使用JavaScript更改href属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆