使用 javascript 更改链接标签的 href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13735247/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:39:07  来源:igfitidea点击:

Changing the href of a link tag using javascript

javascripthtmlcsshreflink-tag

提问by Mikey

Hi I am trying to change the href of a link tag so that when a button is pressed a new style sheet is loaded. This is what I have so far-

嗨,我正在尝试更改链接标签的 href,以便在按下按钮时加载新的样式表。这是我迄今为止所拥有的-

function addcss()
{   
   var findlink = document.getElementsByTagName("link");
   findlink.href = "stylesheetxhtml.css";
}

Any Help Much appreciated Thanks

任何帮助非常感谢谢谢

回答by bfavaretto

You can't set the hrefdirectly like that, because document.getElementsByTagNamereturns all the <link>tags (as a NodeList). If you're positive you only have one, use this:

您不能href像那样直接设置,因为document.getElementsByTagName返回所有<link>标签(作为NodeList)。如果您确定只有一个,请使用以下命令:

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

If you have multiple <link>elements and want to target a specific one, give it an id and use document.getElementById:

如果您有多个<link>元素并希望针对特定元素,请为其指定一个 id 并使用document.getElementById

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

Finally, if you want to create a new <link>element, use document.createElement:

最后,如果要创建新<link>元素,请使用document.createElement

var newLink = document.createElement('link');
newLink.href = "stylesheetxhtml.css";
document.getElementsByTagName("head")[0].appendChild(newlink);