删除iframe时,如何触发iframe的卸载事件?
使用下面的代码,当调用removeChild(iframe)时,不会触发onunload事件。
<!-- parent.html -->
<html>
<head>
<title>remove iframe</title>
<script type="text/javascript">
window.onload = function() {
var button = document.getElementsByTagName("BUTTON")[0];
button.onclick = function() {
document.body.removeChild(document.getElementsByTagName("IFRAME")[0]);
};
};
</script>
</head>
<body>
<iframe src="./son.html" />
<button>Remove iframe</botton>
</body>
</html>
<!-- son.html -->
<html>
<head>
<title>son html</title>
<script type="text/javascript">
window.onload = function() { alert("hello"); };
window.onunload = function() { alert("world!"); };
</script>
</head>
<body style="background-color:#aaccee;">
</body>
</html>
我该如何触发它?
答案 0 :(得分:9)
在删除框架之前,您可以将iframe元素的src属性设置为“about:blank”,检查这是否使iframe触发onunload事件。
EG:
var iframe = document.getElementsByTagName("IFRAME")[0];
iframe.src = "about:blank";
document.body.removeChild(iframe);