【问题标题】:Javascript: replace html class no-js with js [closed]Javascript:用js替换html类no-js [关闭]
【发布时间】:2013-02-20 20:59:03
【问题描述】:

请解释下面这行javascript代码

(function (d, c) {
    d[c] = d[c].replace(/\bno-js\b/, "js");
})(document.documentElement, "className");

这一行替换文档元素类名 例如class="no-js"class="js"

它工作正常,但我不完全理解。 d[c] = d[c].replace???

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    我不知道为什么这被否决了——看起来这是一个关于可变性的好问题。

    原因是字符串是不可变的——你可以用新值替换它们,但你不能改变它们。

    最终结果是

    d[c].replace()
    

    实际上并没有改变值,而是返回一个带有更新值的新字符串。

    只有对返回值进行赋值,才能使源发生变化。

    d[c] = d[c].replace(...)
    

    "进行替换,然后将替换后的值作为原始值"

    【讨论】:

      【解决方案2】:

      Fis 创建函数

      function(d, c){
          d[c] = d[c].replace(/\bno-js\b/,"js");
      }
      

      它用() 包装函数以将其转换为表达式,而不是语句,因此这种方式是可调用的,然后传递参数

      (documentElement, "className")
      

      也就是说,执行以下代码:

      document.documentElement["className"] = document.documentElement["className"].replace(/\bno-js\b/,"js");
      

      然后检索文档的documentElement 属性并根据正则表达式替换其“className”。

      【讨论】:

        【解决方案3】:
        (function(d, c) {
            d[c] = d[c].replace(/\bno-js\b/,"js"); }
        )(document.documentElement, "className");
        

        函数正在使用两个参数调用。为清楚起见,我们将函数中的变量替换为用于调用函数的参数。

        // Find the element in the DOM identified by "documentElement"
        // and access its "className" property, which controls the attribute in
        // the markup called "class"
        document.documentElement["className"] = 
        // Then, take that same property (which is a string), and run
        // .replace() on it, with a regex that says "find no-js separated by word
        // boundaries", and replace that with js
        // Finally, assign the result of that replacement to the original property.
        document.documentElement["className"].replace(/\bno-js\b/,"js");
        

        【讨论】:

          猜你喜欢
          • 2013-02-01
          • 2012-02-01
          • 2016-07-08
          • 1970-01-01
          • 2022-06-14
          • 1970-01-01
          • 2011-10-07
          • 1970-01-01
          • 2016-04-26
          相关资源
          最近更新 更多