IT技术博客大学习 共学习 共进步

动态创建iframe在IE下的两个问题

Heero's Blog 2014-04-15 22:40:29 浏览 2,003 次

表单提交到动态创建的iframe

问题描述

以下代码,一般用于在当前页无刷新提交表单,其原理是把表单的target设为页面上某个iframe的id,使该iframe成为提交的目标,避免新开窗口或跳转。但这段代码在IE 6、7下无效。


<form action="http://www.baidu.com/" method="post" target="testframe">
	<input type="submit" value="Submit" />
</form>
<script>
var iframe = document.createElement('iframe');
iframe.id = 'testframe';
iframe.name = 'testframe';
document.body.insertBefore(iframe, document.body.firstChild);
</script>


解决方案

innerHTML方式插入iframe,例如:


<script>
var div = document.createElement('div');
div.innerHTML = '<iframe id="testframe" name="testframe" />';
document.body.insertBefore(div, document.body.firstChild);
</script>


动态创建iframe的onload事件

问题描述

以下代码在页面中创建一个iframe,并给iframe绑定onload事件回调,但此回调在IE 6、7、8下均无效。


<script>
var iframe = document.createElement('iframe');
iframe.id = 'testframe';
iframe.name = 'testframe';
iframe.src = 'http://www.baidu.com/';
iframe.onload = function() { alert('onload'); };
document.body.insertBefore(iframe, document.body.firstChild);
</script>


解决方案

attachEvent接口绑定事件回调,例如:


<script>
var iframe = document.createElement('iframe');
iframe.id = 'testframe';
iframe.name = 'testframe';
iframe.src = 'http://www.baidu.com/';
var fn = function() { alert('onload'); };
if (iframe.attachEvent) {
	iframe.attachEvent('onload', fn);
} else {
	iframe.onload = fn;
}
document.body.insertBefore(iframe, document.body.firstChild);
</script>

建议继续学习

  1. iframe大小自适应 (阅读 9,883)
  2. iframe里src="about:blank"的问题。 (阅读 7,901)
  3. 跨域请求的iframe解决方案(1) (阅读 6,322)
  4. BO报表系统嵌入Iframe在firefox下的错误修改 (阅读 5,544)
  5. ie下iframe输入框焦点丢失解决方案 (阅读 5,386)
  6. 三谈Iframe自适应高度 (阅读 4,585)
  7. Google+开发团队分享经验 (阅读 4,480)
  8. 使用document.domain和iframe实现站内AJAX跨域 (阅读 4,463)
  9. 跨域请求的iframe解决方案(2) (阅读 4,126)
  10. IFrame带来的Session问题 (阅读 3,945)