为什么使用document.write创建iframe"取消"所有剩余的Javascript?

Mic*_*uez 1 html javascript browser behavior

这种情况发生在所有浏览器中,因此必须有一个原因.

例:

<html>
<body>
<script>var a="support/";
var aa='<iframe src="http://google.com/' + a + '" />'; 
document.write(aa)</script> 
<script>alert('test')</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

iframe写入后的代码(在这种情况下为alert('test'))不会执行.为什么?

Ada*_*rlo 9

因为你正在将破碎的HTML写入文档 - iframe标签上没有>.


sel*_*oup 9

您在文档中写入的HTML无效,导致浏览器无法解释文档的其余部分,包括剩余的<script>标记.

你在写<iframe src="http://google.com/support/.添加"></iframe>它没关系.

但是,更简洁的方法是根本不使用document.write(假设你有一些id ="container"的HTML元素来保存iframe):

var iframe = document.createElement('iframe');
iframe.setAttribute("src", "http://google.com/support/");
document.getElementById("container").appendChild(iframe);
Run Code Online (Sandbox Code Playgroud)