【问题标题】:Changing the stylesheet from index.html从 index.html 更改样式表
【发布时间】:2015-08-27 10:53:45
【问题描述】:

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

我尝试过的:

Index.html

<!DOCTYPE html>
<html>
    <head>
        <link id="style" rel="stylesheet" type="text/css" href="red-stylesheet.css" />
    </head>
</html>

Javascript

function swapStyle(sheet) {
    document.getElementById('#style').setAttribute('href', sheet);
}

其中sheetblue-stylesheet.cssred-stylesheet.css,但我不断收到此错误:

不能为未定义或为空的引用“设置属性”

所以我猜我无法从我的 index.html 访问链接

这是我的文件结构:

views (folder)
  -> settings (folder)
    ->  settings.js (javascript)

index.html (html with the <link>)

【问题讨论】:

  • 看起来id 中的&lt;link&gt; 不是#style ..?
  • 你正在将 js 与 jQuery document.getElementById('style').setAttribute('href', sheet); 混合,而没有 #
  • 我的错误。正如@Pepo_rasta 所说,我在混音。

标签: javascript jquery html css


【解决方案1】:

您的 Javascript 有点过时了。选择器中不需要#

function swapStyle(sheet) {
    document.getElementById('style').setAttribute('href', sheet);
}

【讨论】:

    【解决方案2】:

    试试:

    function swapStyle(sheet) {
        document.getElementById('style').setAttribute('href', sheet);
    }
    

    id前的#只有JQuery才需要

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      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');
          }
      ]
      

      【讨论】:

        【解决方案4】:

        尝试:

        document.getElementsByTagName('head')[0].getElementsByTagName('link')[0].setAttribute('href', sheet);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-11
          • 1970-01-01
          • 1970-01-01
          • 2012-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多