为什么这会执行 <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
看到它执行 .append
。 append
依次调用 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/