5

移除 iframe 时如何触发 iframe 的 unload 事件?

使用下面的代码,当调用 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>

我怎样才能触发它?

4

1 回答 1

11

在移除框架之前,您可以将 iframe 元素的 src 属性设置为“about:blank”,检查这是否会使 iframe 触发 onunload 事件。

例如:

var iframe = document.getElementsByTagName("IFRAME")[0];
iframe.src = "about:blank";
document.body.removeChild(iframe);
于 2011-12-30T07:23:06.807 回答