2011-12-30 46 views
4

如何刪除iframe的卸載事件時觸發?如何在刪除iframe時觸發onunload事件?

使用下面的代碼調用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> 

我該如何觸發它?

回答

8

在刪除框架之前,您可以將iframe元素的src屬性設置爲「about:blank」,檢查是否使iframe觸發onunload事件。

EG:

var iframe = document.getElementsByTagName("IFRAME")[0]; 
iframe.src = "about:blank"; 
document.body.removeChild(iframe); 
+0

在Firefox的偉大工程,但不能在Chrome中。有任何想法嗎? – ipinyol 2014-11-26 12:05:23