【问题标题】:JavaScript - Replacing "no-js" class with "js" class not working?JavaScript - 用“js”类替换“no-js”类不起作用?
【发布时间】:2013-02-01 12:03:48
【问题描述】:

我在 <html> 元素中放置了一个名为“no-js”的类。这表明用户没有使用 javascript,(无论是被禁用还是被阻止)。然后,在我创建的脚本文件中,我想撤销“no-js”并注入“js”,以便我可以确定用户是否通过类使用 javascript。我尝试通过查询 html 标签来使用replace() 方法,但它不起作用。这是我所拥有的:

var html = document.getElementsByTagName("html")[0];
if(html.className == "no-js") {
    html.className.replace("no-js", "js"); // user has JS enabled
} 

Google Chrome 或 Firefox 的错误控制台中没有错误,但也没有将 no-js 更改为 js。我会使用<noscript> 标签,但我喜欢保持它的标记部分干净。

【问题讨论】:

  • 它不会就地替换。你必须做html.className = html.className.replace("no-js", "js");
  • html.classList.remove('no-js'); html.classList.add('js');

标签: javascript html class replace classname


【解决方案1】:

replace 返回新字符串,不修改原来的字符串。

尝试html.className = 'js',因为您已经确定它是您的if 语句中唯一的类名。

编辑:另外,<html> 标签已经可以作为document.documentElement 使用。

document.documentElement.className = 'js';

这就是你所需要的,真的。没有if 语句,没有变量,什么都没有。

【讨论】:

  • 哦,是的!我认为这会将js 添加 js 到html,而不是替换。但要做到这一点,我必须这样做+=。有效!谢谢!
【解决方案2】:

接受的答案确实是正确的,但是这种方式将替换<html>的所有类,而不仅仅是.no-js

这个小脚本会做同样的事情,但只会搜索 no-js 类并重写它。

document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';

从这里拿脚本,很简单! http://snipplr.com/view/63895/remove-nojs-class-from-html-tag-add-js-class/

【讨论】:

    【解决方案3】:

    您忘记将 html.className 分配给新值:

    var html = document.getElementsByTagName("html")[0];
    if(html.className == "no-js") {
        html.className = html.className.replace("no-js", "js"); // user has JS enabled
    } 
    

    【讨论】:

    • 啊,这也可以,但另一个答案更简单。谢谢!
    【解决方案4】:

    用一点正则表达式

    (function(html) {
      html.className = html.className.replace(/\bno-js\b/, 'js')
    })(document.documentElement);
    <!DOCTYPE html>
    <html class="no-js">
    <head>
    	
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多