为什么html()执行JavaScript,但innerHTML不执行? [英] Why does html() execute JavaScript, but innerHTML doesn't?

查看:905
本文介绍了为什么html()执行JavaScript,但innerHTML不执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么执行< script>

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

但这不是吗?

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

你可以看到它的实际效果 这里

You can see it in action here

来自jQuery的关于。html()

From jQuery's documentation about .html():


此方法使用浏览器的innerHTML属性。某些浏览器可能不会返回完全复制原始文档中HTML源的HTML。例如,如果Internet Explorer仅包含字母数字字符,则有时会忽略属性值旁边的引号。

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 is a jQuery function. innerHTML is a non-standard (but well supported) property.

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

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

要在源代码中找到它:

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

看到它。附加追加依次调用 DomManip [ulate] 将解析和 eval scripts。

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

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

这篇关于为什么html()执行JavaScript,但innerHTML不执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆