如何在<link />标记内添加href动态

时间:2017-02-28 06:39:17

标签: javascript html angular

我试图在角度2中显示favicon,我通过放置这些线来实现

  <link rel="shortcut icon" type="image/x-icon" href="app/favicon.ico" />

但是,在这里有一个问题我需要刷新我的页面,并在第二次在新的浏览器上显示favicon。但是,我希望favicon能够有力地刷新,因为我正在使用

<link rel="icon" href=http://domainname+"/favicon.ico?v=2"/>
  

为此,我需要动态填充域名

我也使用下面的代码获取主机名

  <script>
    var url = window.location.href
    console.log('Main Loaded '+url);
  </script>

现在我想将url放在域名所在的链接的href中。 请建议我如何做到这一点。

3 个答案:

答案 0 :(得分:0)

可以动态设置链接的href。您必须识别链接并设置元素的href属性,如下面的代码

window.document.getElementsByTagName('link')[0].href = url;

答案 1 :(得分:0)

您无法直接设置href,因为document.getElementsByTagName会返回所有标记(作为NodeList)。如果你是肯定的,你只有一个,请使用:

var findlink = document.getElementsByTagName("link");
findlink[0].href = url;

如果您有多个链接元素并希望定位特定链接元素,请为其指定ID并使用document.getElementById

var findlink = document.getElementsById("myLinkId");
findlink.href = url;

答案 2 :(得分:0)

window.location.href将返回完整路径 因此,请使用window.location.protocol+"//"+window.location.host获取域名

&#13;
&#13;
document.getElementsByTagName('link')[0].href=window.location.protocol+"//"+window.location.host+"/favicon.ico?v=2";
console.log(document.getElementsByTagName('link')[0]);
&#13;
<link rel="icon" href=http://domainname+"/favicon.ico?v=2"/>
&#13;
&#13;
&#13;

要查看差异,请在此处运行

&#13;
&#13;
console.log(window.location.href);
console.log(window.location.protocol);
console.log(window.location.host);
&#13;
&#13;
&#13;