Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从index.html更改样式表_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 从index.html更改样式表

Javascript 从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

我正在尝试实现用户在我的PhoneJS应用程序中更改主题的功能(也可以是常规JS)

我所尝试的:

Index.html

<!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);