标签:
在页面中动态追加html片段的时候,有时候动态添加的代码会含有<script>标签,比如用了一些模板引擎,或者你的代码有些复杂的时候。然而我们用DOM提供的innerHTML方式来添加代码的时候,<script>标签中的代码并不能执行,如果有src属性,指向的外联文件也不会被加载,这并不是浏览器的bug,因为w3c文档就是这么规定的。
<div id="cont"></div>
var html = ‘<div>html</div><script>alert(1);<\/script>‘; var cont = document.getElementById(‘cont‘); cont.innerHTML = html; var oldScript = cont.getElementsByTagName(‘script‘)[0]; cont.removeChild(oldScript); var newScript = document.createElement(‘script‘); newScript.type = ‘text/javascript‘; newScript.innerHTML = oldScript.innerHTML; cont.appendChild(newScript);
var html = ‘<div>html</div><script>alert(1);<\/script>‘; var cont = document.getElementById(‘cont‘); cont.innerHTML = html; var oldScript = cont.getElementsByTagName(‘script‘)[0]; cont.removeChild(oldScript); var scriptText = oldScript.innerHTML; eval(scriptText);
var html = ‘<div>html</div><script>alert(1);<\/script>‘; document.write(html);
<div id="cont"><script type="text/javascript">document.write(html);</script></div>
var html = ‘<div>html</div><script>alert(1);<\/script>‘; $(‘#cont‘).html(html);
标签:
原文地址:http://www.cnblogs.com/lvdabao/p/4253704.html