javascript - 为什么 html() 执行 JavaScript,而 innerHTML 不执行?

标签 javascript jquery innerhtml

为什么这会执行 <script> :

$('#jq_script').html("<script>$('#test').text('test');<\/script>");

但这不是吗?

document.getElementById('js_script').innerHTML = "<script>$('#test').text('test');<\/script>";

你可以看到它的实际效果 here

来自 jQuery 关于 .html() 的文档:

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

最佳答案

html 是一个 jQuery 函数。 innerHTML 是一个非标准(但得到很好支持)的属性。

如果您查看代码,您会看到 .html() 解析脚本,并eval它们。


在源代码中找到它:

找到 html 声明:https://github.com/jquery/jquery/blob/1.11.0/src/manipulation.js#L564-604

看到它执行 .appendappend 依次调用 DomManip[ulate],它将解析和eval 脚本。

DomManip[ulate] 中的相关位:https://github.com/jquery/jquery/blob/1.11.0/src/manipulation.js#L684-709

关于javascript - 为什么 html() 执行 JavaScript,而 innerHTML 不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734588/

相关文章:

Javascript forEach 函数覆盖自身

javascript - jQuery 扩展我的垂直标签

javascript - 每 15 秒加载完所有内容后刷新页面

javascript - 如何直接链接到由 innerHTML 生成的 div?

javascript - 禁用/启用按钮 - jquery

javascript - 检测服务是否可用的最佳实践

javascript - 使用 jQuery 改变点击背景颜色

javascript - 如何将 javascript 文件中的变量放入 HTML 文件中的元素中?

javascript - JQuery 切换/html : changing the content in div

javascript - 提交时从 Rails 表单中删除必需的属性?