我想创建一个javascript文件(附加到某个网站),它会生成可用的样式表,而单击某个名称会更改所选样式的当前样式表。我这样做:
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = document.getElementsByTagName("link").item(i).href //getting name
//and here is my problem - I'd like to change that HTML code to js code, so that it generates a link wchich should change the style. I can't figure it out how to change that to js.
<a href="#" onclick="changeCSS(style, 0);">STYLE 3</a>
}
//这是更改样式表的函数(不是我的,但正在工作)
function changeCSS(cssFile, cssLinkIndex)
{
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link")
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
您能否请验证我的代码并帮助我更改带有链接的HTML代码到js代码?
//修改
我很抱歉,但它仍然无法运行...我正在使用该代码的网站有3个样式表,但我没有结果。
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = new String(document.getElementsByTagName("link").item(i).href));
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
a.onclick = function(){ changeCSS(style,0)}; // When you click it, you call changeCSS
document.body.appendChild(a); // Append it to the body
}
我使用了你的代码,如上所述。
答案 0 :(得分:1)
在你的循环中:
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
// When you click it, you call changeCSS
a.onclick = function(){ changeCSS(style,0)};
document.body.appendChild(a); // Append it to the body
如果要将其附加到其他元素,请更改
document.body.appendChild(a);
要
whatEverElement.appendChild(a);
一些评论:
appendChild
添加一个元素作为另一个元素的子元素,就像在changeCSS
textContent
和innerText
以支持旧IE,如果您不需要,请单独更改为textContent
。请注意,它不使用更改CSS,而是警告,因为我不知道如何在JSFiddle中加载外部工作表。