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

纵然是瞬间 提交于 2019-12-10 13:09:18

问题


Why does this execute the <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():

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.


回答1:


html is a jQuery function. innerHTML is a non-standard (but well supported) property.

If you look at the code you will see that .html() parses scripts, and evals them.


To find it in the source:

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

See it does .append. append in turn calls DomManip[ulate] which will parse and eval scripts.

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



来源:https://stackoverflow.com/questions/21734588/why-does-html-execute-javascript-but-innerhtml-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!