Javascript 从index.html更改样式表
我正在尝试实现用户在我的PhoneJS应用程序中更改主题的功能(也可以是常规JS) 我所尝试的: Index.htmlJavascript 从index.html更改样式表,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试实现用户在我的PhoneJS应用程序中更改主题的功能(也可以是常规JS) 我所尝试的: Index.html <!DOCTYPE html> <html> <head> <link id="style" rel="stylesheet" type="text/css" href="red-stylesheet.css" /> </head> </html> 其中sheet是blue
<!DOCTYPE html>
<html>
<head>
<link id="style" rel="stylesheet" type="text/css" href="red-stylesheet.css" />
</head>
</html>
其中sheet
是blue stylesheet.css
或red stylesheet.css
,但我一直收到以下错误:
无法为未定义或空的引用设置“setAttribute”
所以我猜我无法从index.html访问链接
这是我的文件结构:
views (folder)
-> settings (folder)
-> settings.js (javascript)
index.html (html with the <link>)
视图(文件夹)
->设置(文件夹)
->settings.js(javascript)
index.html(带有
您的Javascript有点过时。选择器中不需要#
function swapStyle(sheet) {
document.getElementById('style').setAttribute('href', sheet);
}
您可以尝试以下方法:
function swapStyle(sheet) {
$('link[href="blue-stylesheet.css"]').attr('href','red-stylesheet.css');
}
或者,如果需要,您可以将其封装在if语句中,如:
function swapStyle(sheet) {
if($("link[rel='stylesheet']").attr("href") == "blue-stylesheet.css") {
$('link[href="blue-stylesheet.css"]').attr('href','red-stylesheet.css');
} else {
$('link[href="red-stylesheet.css"]').attr('href','blue-stylesheet.css');
}
]
尝试:
id之前的#仅在JQuery中需要
尝试:
看起来
中的id
不是#style
。?您将js与jQuery文档混合在一起。getElementById('style')。setAttribute('href',sheet)代码>没有我的错误。正如@Pepo_rasta所说的,我在混合。可能是重复的
function swapStyle(sheet) {
if($("link[rel='stylesheet']").attr("href") == "blue-stylesheet.css") {
$('link[href="blue-stylesheet.css"]').attr('href','red-stylesheet.css');
} else {
$('link[href="red-stylesheet.css"]').attr('href','blue-stylesheet.css');
}
]
function swapStyle(sheet) {
document.getElementById('style').setAttribute('href', sheet);
}
document.getElementsByTagName('head')[0].getElementsByTagName('link')[0].setAttribute('href', sheet);