微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么html()执行JavaScript,但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()解析脚本,然后逐出它们.

要在源中找到它:

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

看它确实.append.依次调用DomManip [ulate]来解析和评估脚本.

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

原文地址:https://www.jb51.cc/html/223935.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐