JQuery html() 与 innerHTML

发布于 2024-09-15 20:59:54 字数 561 浏览 5 评论 0原文

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

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

该应用程序在 Firefox 上运行良好,但 Internet Explorer 引发错误:未知的运行时异常。我使用了 jQuery 的 html() 方法,IE 的错误消失了。但我不确定它是否适用于所有浏览器,并且我不确定是否用 jQuery 的 html() 方法替换所有 innerHTML 属性。

多谢。

Can I completely rely upon jQuery's html() method behaving identical to innerHTML? Is there any difference between innerHTML and jQuery's html() method? If these methods both do the same, can I use jQuery's html() method in place of innerHTML?

My problem is: I am working on already designed pages, the pages contains tables and in JavaScript the innerHTML property is being used to populate them dynamically.

The application is working fine on Firefox but Internet Explorer fires an error: unknown runtime exception. I used jQuery's html() method and IE's error has disappeared. But I'm not sure it will work for all browsers and I'm not sure whether to replace all innerHTML properties with jQuery's html() method.

Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

请帮我爱他 2024-09-22 20:59:54

回答你的问题:

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

To answer your question:

.html() will just call .innerHTML after doing some checks for nodeTypes and stuff. It also uses a try/catch block where it tries to use innerHTML first and if that fails, it'll fallback gracefully to jQuery's .empty() + append()

萌吟 2024-09-22 20:59:54

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

在 Internet Explorer 7 或 8 中运行此命令,您就会看到。

当设置包含

的 HTML 时,jQuery 会生成错误的 HTML嵌套在

内的标签字符串开头是换行符的标记!

这里有几个测试用例,运行时的注释应该足够不言自明。这是相当晦涩的,但不理解发生了什么有点令人不安。我将提交一份错误报告。

<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>

Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!

Run this in internet explorer 7 or 8 and you'll see.

jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!

There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.

<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>
不喜欢何必死缠烂打 2024-09-22 20:59:54

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

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

If you're wondering about functionality, then jQuery's .html() performs the same intended functionality as .innerHTML, but it also performs checks for cross-browser compatibility.

For this reason, you can always use jQuery's .html() instead of .innerHTML where possible.

晨与橙与城 2024-09-22 20:59:54

鉴于目前 .innerHTML 的普遍支持,唯一有效的现在的区别是 .html()执行任何

来自 jQuery 文档

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

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

Given the general support of .innerHTML these days, the only effective difference now is that .html() will execute code in any <script> tags if there are any in the html you give it. .innerHTML, under HTML5, will not.

From the jQuery docs:

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

Note: both .innerHTML and .html() can execute js other ways (e.g the onerror attribute).

傲鸠 2024-09-22 20:59:54

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

innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.

网名女生简单气质 2024-09-22 20:59:54

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

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

"This method uses the browser's innerHTML property." - jQuery API

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

撩心不撩汉 2024-09-22 20:59:54

这里有一些代码可以帮助您入门。您可以修改 .innerHTML 的行为 - 您甚至可以创建自己的完整 .innerHTML shim。 (PS:重新定义 .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/

Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)

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/

℉絮湮 2024-09-22 20:59:54

一个关键的区别是 jQuery 的 .html() 方法执行 HTML 内的任何内联

这对我来说很关键,因为我使用 fetch 请求来获取 response,该响应的 HTML 内有

jAndy 提到还有类型检查。

要执行脚本,请检查 RedRiderX 在上述评论中链接的问题:如何在通过 ajax 加载的 html 中运行 javascript


jQuery .html() 文档,这对于这个利基问题不是很有帮助:https://api.jquery.com/html/

A key difference is that jQuery's .html() method executes any inline <script> tags inside the HTML.

This was key for me as I was using a fetch request to get a response that had HTML that had <script> tags inside as part of making a modal work in WordPress. It wasn't working and I narrowed it down to .html() vs .innerHTML which I thought were identical. After console logging the response and copying it to a file and searching for <script> I found the code that was being run with .html() and not with .innerHTML.

There is also type checking as mentioned by jAndy.

For executing the scripts, check this question linked in the above comments by RedRiderX: how to run javascript in html loaded via ajax


jQuery .html() documentation, which isn't super helpful for this niche question: https://api.jquery.com/html/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文