为什么使用document.write创建一个iframe [取消了"所有剩余的Javascript? [英] Why does using document.write to create an iframe "cancel out" all remaining Javascript?

查看:210
本文介绍了为什么使用document.write创建一个iframe [取消了"所有剩余的Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这发生在所有的浏览器,所以必须有一个原因。

This happens in all browsers, so there must be a reason.

例如:

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

在iframe写后,code(在这种情况下,警报('测试'))不执行。为什么呢?

The code after the iframe write (in this case alert('test')) doesn't execute. Why?

推荐答案

您的HTML,你写入该文件是无效的,会导致浏览器出现故障间preting文档的其余部分,包括剩余的&LT;脚本方式&gt; 标签

Your HTML that you write into the document is invalid and causes the browser to fail interpreting the rest of the document, including the remaining <script> tags.

您正在写&LT; IFRAME SRC =htt​​p://google.com/support/ 添加。&GT;&LT; / IFRAME&GT ; 键,它的确定

You are writing <iframe src="http://google.com/support/. Add "></iframe> and it's ok.

然而,一个更简洁的方法将不使用文件撰写在所有(假设你有一个ID =容器持有的iframe一些HTML元素):

However, a cleaner approach would be not to use document.write at all (assuming you have some HTML element with id="container" to hold the iframe):

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

这篇关于为什么使用document.write创建一个iframe [取消了&QUOT;所有剩余的Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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