可以使用innerHTML插入脚本吗? [英] Can scripts be inserted with innerHTML?
问题描述
我尝试使用< div>
中的 innerHTML
将一些脚本加载到页面中。看来脚本加载到DOM中,但是它永远不会执行(至少在Firefox和Chrome中)。在使用 innerHTML
插入脚本时,是否有脚本执行?
I tried to load some scripts into a page using innerHTML
on a <div>
. It appears that the script loads into the DOM, but it is never executed (at least in Firefox and Chrome). Is there a way to have scripts execute when inserting them with innerHTML
?
示例代码:
<!DOCTYPE html>
<html>
<body onload="document.getElementById('loader').innerHTML = '<script>alert(\'hi\')<\/script>'">
Shouldn't an alert saying 'hi' appear?
<div id="loader"></div>
</body>
</html>
推荐答案
您必须使用 eval()来执行任何脚本代码您已经以DOM文本的形式插入了。
You have to use eval() to execute any script code that you've inserted as DOM text.
MooTools会为您自动执行此操作,我确定jQuery也可以(取决于版本)jQuery版本1.6 +使用 eval
)。这节省了很多麻烦,解析出< script>
标签和转义您的内容,以及一堆其他getchas。
MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval
). This saves a lot of hassle of parsing out <script>
tags and escaping your content, as well as a bunch of other "gotchas".
一般来说,如果你要自己去 eval()
,你想创建/发送没有任何HTML标记的脚本代码,如< script>
,因为这些不会正确地 eval()
Generally if you're going to eval()
it yourself, you want to create/send the script code without any HTML markup such as <script>
, as these will not eval()
properly.
这篇关于可以使用innerHTML插入脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!