如何在iframe加载后创建iframe并销毁元素?

joh*_*ohn 3 javascript

我能够使用appendChild创建一个iframe,没有jquery,我是否可以知道iframe何时加载然后能够销毁该元素?

Sha*_*haz 7

您可以使用该onLoad活动.

 <iframe onload="this.parentNode.removeChild(this);" src="/"></iframe>
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/mSZ4X/1/

或者使用纯JavaScript:

var iframe = document.createElement("iframe");

iframe.src = "/";
iframe.onload = function() {
    this.parentNode.removeChild(this);    
};

document.body.appendChild(iframe);
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/mSZ4X/2/