【问题标题】:Javascript difference between IE and FirefoxIE 和 Firefox 之间的 Javascript 区别
【发布时间】:2010-07-31 13:02:22
【问题描述】:

我有以下几行 Javascript:

 var button = document.getElementById("scriptsubmit");
 button.setAttribute("class", "remove");

在 Firefox 中可以完美运行,而在 Internet Explorer 中则不行。

我知道 Internet Explorer 期望 class 为 className,但我不确定如何检测使用哪个作为对象检测在这种情况下似乎不适用。

感谢您的回复

【问题讨论】:

  • 确实,您永远不应该在 HTML 文档上使用 getAttribute/setAttribute。它在 IE 中存在问题,并且比使用 DOM Level 1 HTML 属性(如 button.className)更易读。

标签: javascript object-detection


【解决方案1】:

您可以在两个浏览器中直接使用 className 属性:

var button = document.getElementById("scriptsubmit");
button.className = "remove";

【讨论】:

    【解决方案2】:

    两个浏览器都支持className,所以不需要检测任何东西。

    【讨论】:

    • 除非我的 Firefox 版本被破坏,否则这是不正确的。
    • 是的,但是不能用“setAttribute”/“getAttribute”访问。
    • ...反正不是我在问题中尝试的方式
    【解决方案3】:

    根据这些测试,setAttribute() 在 IE 中不完全支持: http://www.quirksmode.org/dom/w3c_core.html#t1110

    解决这个问题的一种方法是创建一个新的 HTML 元素,设置它的属性,然后用它替换按钮,如下所示:

    var newButton=document.createElement("button");
    newButton.class="remove";
    
    var oldButton=document.getElementById("button");
    document.removeChild(oldButton);
    document.appendChild(newButton);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2011-07-19
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多