开发者

Dynamic iframe onload not firing?

I figure this is possible because there are a ton of similar questions (that have been solved) but none seem to deal with dynamically created iframes.

Basically I'm using jquery to create a temp iframe to load files (from a file p开发者_运维知识库ath served through an ajax call) to then open a file download prompt.

Everything works but to keep my DOM from being populated by a bunch of iframes I would like the iframes to be removed once the file is downloaded.

My iframe creation code:

$('<iframe class="downloadIFrame" src="'+data['url']+'"></iframe>').appendTo('body');

And the code to destroy it (in the "ready" jquery event callback):

$('.downloadIFrame').live('load', function() { alert('loaded');$(this).remove(); });

I don't get the alert that the iframe was loaded so it's not called. Any clue?


live works on event bubbling mechanism where as iframe load event is not user action triggered. So you cannot use live to handle the iframe load event.

Also before setting the src of the iframe you should attach the iframe load event handler. This is to avoid the case when iframe gets loaded before the load event is attached.

Try this

$('<iframe class="downloadIFrame"></iframe>')
.appendTo('body')
.load(function(){
   $(this).remove();
}).attr("src", data['url']);


Don’t use a live listener.

$('<iframe class="downloadIFrame" src="http://www.google.com/"></iframe>').appendTo('body');
$('.downloadIFrame').load(function() { alert('loaded');$(this).remove(); });

Works fine for me in Webkit.


I would try putting the alert code in the dom of the iframe you've created - it has its own dom, thus its own event hierarchy etc.

Think of it as a totally separate page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜