简体   繁体   English

为什么html()执行JavaScript,但innerHTML不执行?

[英]Why does html() execute JavaScript, but innerHTML doesn't?

Why does this execute the <script> : 为什么这会执行<script>

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

But this doesn't? 但这不是吗?

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

You can see it in action here 你可以在这里看到它

From jQuery's documentation about .html() : 来自jQuery的关于.html()的文档:

This method uses the browser's innerHTML property . 此方法使用浏览器的innerHTML属性 Some browsers may not return HTML that exactly replicates the HTML source in an original document. 某些浏览器可能不会返回完全复制原始文档中HTML源的HTML。 For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters. 例如,如果Internet Explorer仅包含字母数字字符,则有时会忽略属性值周围的引号。

html is a jQuery function. html是一个jQuery函数。 innerHTML is a non-standard (but well supported) property. innerHTML是一种非标准(但受到良好支持)的属性。

If you look at the code you will see that .html() parses scripts, and eval s them. 如果查看代码,您将看到.html()解析脚本,并对它们进行eval


To find it in the source: 要在源中找到它:

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

See it does .append . 看它确实.append append in turn calls DomManip[ulate] which will parse and eval scripts. append依次调用DomManip[ulate]将解析和eval脚本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM