【问题标题】:JQuery html() vs. innerHTMLJQuery html() 与 innerHTML
【发布时间】:2011-04-03 13:10:54
【问题描述】:

我可以完全依赖 jQuery 的 html() 方法,其行为与 innerHTML 相同吗? innerHTML 和 jQuery 的 html() 方法有什么区别吗?如果这两个方法都一样,我可以用jQuery的html()方法代替innerHTML吗?

我的问题是:我正在处理已经设计好的页面,页面包含表格,并且在 JavaScript 中,innerHTML 属性用于动态填充它们。

应用程序在 Firefox 上运行良好,但 Internet Explorer 触发错误:unknown runtime exception。我使用了 jQuery 的 html() 方法,IE 的错误消失了。但我不确定它是否适用于所有浏览器,我不确定是否将所有 innerHTML 属性替换为 jQuery 的 html() 方法。

非常感谢。

【问题讨论】:

  • 使用 jQuery html()。我在很多场合都遇到过innerHTML 的问题。并且 html() 将适用于所有浏览器。

标签: javascript jquery html dom innerhtml


【解决方案1】:

回答你的问题:

.html() 将在对 nodeTypes 和其他内容进行一些检查后调用.innerHTML。它还使用try/catch 块,它首先尝试使用innerHTML,如果失败,它将优雅地回退到jQuery 的.empty() + append()

【讨论】:

  • 请注意,对于 Internet Explorer 8(很可能是更早版本),附加检查可能会为大型插入增加显着的性能损失,因此如果 IE 上的性能很重要,您可能需要考虑直接使用 innerHTML .
【解决方案2】:

特别是关于“我可以完全依赖 jquery html() 方法,它会像 innerHTML 一样执行吗”,我的答案是否定的!

在 internet explorer 7 或 8 中运行它,你会看到。

当设置 HTML 包含嵌套在

标记中的

标记时,jQuery 会产生错误的 HTML,其中字符串的开头是换行符!

这里有几个测试用例,运行时的 cmets 应该足够自我解释。这很模糊,但不了解发生了什么有点令人不安。我要提交错误报告。

<html>

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>   

        <script>
            $(function() {

                // the following two blocks of HTML are identical except the P tag is outside the form in the first case
                var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
                var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";

                // <FORM> tag nested within <P>
                RunTest("<FORM> tag nested within <P> tag", html1);                 // succeeds in Internet Explorer    
                RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1);     // fails with added new line in Internet Explorer


                // <P> tag nested within <HTML>
                RunTest("<P> tag nested within <FORM> tag", html2);                 // succeeds in Internet Explorer
                RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2);     // succeeds in Internet Explorer even with \n

            });

            function RunTest(testName, html) {

                // run with jQuery
                $("#placeholder").html(html);
                var jqueryDOM = $('#placeholder').html();
                var jqueryFormSerialize = $("#placeholder form").serialize();

                // run with innerHTML
                $("#placeholder")[0].innerHTML = html;

                var innerHTMLDOM = $('#placeholder').html();
                var innerHTMLFormSerialize = $("#placeholder form").serialize();

                var expectedSerializedValue = "field1=111&field2=222";

                alert(  'TEST NAME: ' + testName + '\n\n' +
                    'The HTML :\n"' + html + '"\n\n' +
                    'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
                    'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +

                    'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +

                    'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
                    'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +

                    'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
                    'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") 

                    );
            }

        </script>
    </head>

    <div id="placeholder">
        This is #placeholder text will 
    </div>

</html>

【讨论】:

  • 我认为这个错误报告回来告诉我关于

    标记中允许的内容我有无效的 HTML - 或类似的东西。这是很久以前的事了,所以我不确定是否有任何改变,但是 3 年后这仍然得到了支持,所以如果有人要添加任何内容,请添加评论

  • 这在 IE9 中仍然存在,只需尝试一下:$("body").html("

    看看我在那里做了什么?
    ");
【解决方案3】:

如果您想了解功能,那么 jQuery 的 .html() 执行与 .innerHTML 相同的预期功能,但它还执行跨浏览器兼容性检查。

因此,您始终可以尽可能使用 jQuery 的 .html() 而不是 .innerHTML

【讨论】:

  • innerHTML 是文档/元素属性的属性,而不是方法。
【解决方案4】:

innerHTML 不是标准的,在某些浏览器中可能不起作用。我在所有浏览器中都使用了 html() 没有问题。

【讨论】:

【解决方案5】:

考虑到如今的general support of .innerHTML,现在唯一有效的区别是.html()执行任何&lt;script&gt; 标记中的代码(如果您提供的html 中有任何标记)。 .innerHTMLunder HTML5,不会。

来自the jQuery docs

根据设计,任何接受 HTML 字符串的 jQuery 构造函数或方法(jQuery()、.append()、.after() 等)都可能执行代码。这可以通过注入脚本标签或使用执行代码的 HTML 属性(例如,&lt;img onload=""&gt;)来实现。不要使用这些方法插入从 URL 查询参数、cookie 或表单输入等不受信任的来源获得的字符串。这样做可能会引入跨站点脚本 (XSS) 漏洞。在向文档添加内容之前删除或转义任何用户输入。

注意:.innerHTML.html() 都可以通过其他方式执行 js(例如 onerror 属性)。

【讨论】:

  • 非常有趣。那么如何强制 HTML5 在插入时执行
  • 它有点老了,但我仍然认为另一个answer's solution 今天会很好用。如果你使用 jQuery,你当然可以只使用 .html()。
  • 现在我再看一遍,这个答案确实错过了从更大的 html 片段中解析 script 标记的步骤。也许需要一个新的问题/答案?
【解决方案6】:

"此方法使用浏览器的 innerHTML 属性。" - jQuery API

http://api.jquery.com/html/

【讨论】:

    【解决方案7】:

    这里有一些代码可以帮助您入门。您可以修改 .innerHTML 的行为——您甚至可以创建自己的完整 .innerHTML shim。 (P.S.:重新定义 .innerHTML 也适用于 Firefox,但不适用于 Chrome——他们正在努力。)

    if (/(msie|trident)/i.test(navigator.userAgent)) {
     var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
     var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
     Object.defineProperty(HTMLElement.prototype, "innerHTML", {
      get: function () {return innerhtml_get.call (this)},
      set: function(new_html) {
       var childNodes = this.childNodes
       for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
        this.removeChild (childNodes[0])
       }
       innerhtml_set.call (this, new_html)
      }
     })
    }
    
    var mydiv = document.createElement ('div')
    mydiv.innerHTML = "test"
    document.body.appendChild (mydiv)
    
    document.body.innerHTML = ""
    console.log (mydiv.innerHTML)
    

    http://jsfiddle.net/DLLbc/9/

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      相关资源
      最近更新 更多