Javascript JQuery html() 与 innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3563107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery html() vs. innerHTML
提问by Bhupi
Can I completely rely upon jQuery's html()method behaving identical to innerHTML? Is there any difference between innerHTMLand jQuery's html()method? If these methods both do the same, can I use jQuery's html()method in place of innerHTML?
我可以完全依赖 jQuery 的html()行为方式innerHTML吗?innerHTML和 jQuery 的html()方法有什么区别吗?如果这些方法都做同样的事情,我可以使用 jQuery 的html()方法来代替innerHTML吗?
My problem is: I am working on already designed pages, the pages contains tables and in JavaScript the innerHTMLproperty is being used to populate them dynamically.
我的问题是:我正在处理已经设计好的页面,页面包含表格,并且在 JavaScript 中,该innerHTML属性用于动态填充它们。
The application is working fine on Firefoxbut Internet Explorerfires 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 innerHTMLproperties with jQuery's html()method.
该应用程序在Firefox上运行良好,但Internet Explorer引发错误:unknown runtime exception。我使用了 jQuery 的html()方法,IE的错误消失了。但我不确定它是否适用于所有浏览器,我不确定是否innerHTML用 jQuery 的html()方法替换所有属性。
Thanks a lot.
非常感谢。
回答by jAndy
To answer your question:
回答你的问题:
.html()will just call .innerHTMLafter doing some checks for nodeTypes and stuff. It also uses a try/catchblock where it tries to use innerHTMLfirst and if that fails, it'll fallback gracefully to jQuery's .empty()+ append()
.html()将.innerHTML在对 nodeTypes 和其他东西进行一些检查后调用。它还使用一个try/catch块,它innerHTML首先尝试使用,如果失败,它将优雅地回退到 jQuery 的.empty()+append()
回答by Simon_Weaver
Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!
特别是关于“我可以完全依赖 jquery html() 方法,它会像 innerHTML 一样执行吗”我的答案是否定的!
Run this in internet explorer 7 or 8 and you'll see.
在 Internet Explorer 7 或 8 中运行它,您会看到。
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!
当设置包含嵌套在 <P> 标记中的 <FORM> 标记的 HTML 时,jQuery 会产生错误的 HTML,其中字符串的开头是换行符!
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>
回答by David Tang
If you're wondering about functionality, then jQuery's .html()performs the same intendedfunctionality as .innerHTML, but it also performs checks for cross-browser compatibility.
如果您想了解功能,那么 jQuery 会.html()执行与 相同的预期功能.innerHTML,但它还执行跨浏览器兼容性检查。
For this reason, you can always use jQuery's .html()instead of .innerHTMLwhere possible.
出于这个原因,您始终可以使用 jQuery.html()而不是.innerHTML在可能的情况下。
回答by Craig
innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.
innerHTML 不是标准的,可能无法在某些浏览器中使用。我在所有浏览器中都使用过 html() 没有问题。
回答by codersarepeople
"This method uses the browser's innerHTML property." - jQuery API
“此方法使用浏览器的innerHTML 属性。” - jQuery API
回答by RedRiderX
Given the general support of .innerHTMLthese days, the only effective difference now is that .html()will execute code in any <script>tagsif there are any in the html you give it. .innerHTML, under HTML5, will not.
鉴于这些天的普遍支持,.innerHTML现在唯一有效的区别是,如果您提供的 html 中有任何标签,.html()则将执行任何<script>标签中的代码。.innerHTML,在 HTML5 下,不会。
From the jQuery docs:
来自jQuery 文档:
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.
按照设计,任何接受 HTML 字符串的 jQuery 构造函数或方法——jQuery()、.append()、.after() 等——都可能执行代码。这可以通过注入脚本标签或使用执行代码的 HTML 属性(例如,
<img onload="">)来发生。不要使用这些方法插入从不受信任的来源获取的字符串,例如 URL 查询参数、cookie 或表单输入。这样做可能会引入跨站点脚本 (XSS) 漏洞。在向文档添加内容之前删除或转义任何用户输入。
Note: both .innerHTMLand .html()can execute js other ways (e.g the onerrorattribute).
注:两者.innerHTML并.html()可以执行JS其他方式(如onerror属性)。
回答by Agamemnus
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.)
这是一些帮助您入门的代码。您可以修改 .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)

