2010-09-28 63 views
2

我试图重新加载一个iframe类似如下:IFRAME .load事件不触发

var frameObject = $('#myFrame'); 
var frameAsInDom = frameObject[0].contentWindow; 
var currenctLocation = frameAsInDom.location; 
frameObject.attr('src', 'about:blank'); 
frameObject.contents().remove(); // This was a desperate statement!! 
frameObject.attr('src', currentLocation).load(function(){ 
    alert('iframe reloaded'); 
}); 

问题是iframe的.load事件没有得到触发的。我没有收到负载回拨内的警报

回答

5

你混合绑定和事件的触发,

错字看到这个代码:http://jsfiddle.net/BvQuk/1/

HTML

<iframe id="myFrame" src="http://google.com"></iframe><br/> 
<input id="uxButton" type="button" value="Reload the frame" /> 

JS

$(document).ready(function() { 
    var iFrame = $('#myFrame'); 

    iFrame.bind('load', function() { //binds the event 
     alert('iFrame Reloaded'); 
    }); 

    $('#uxButton').click(function() { 
     alert('onButtonClick OR onBeforeReload'); 
     var newSrc = iFrame.attr('src') + '?c=' + Math.random(); //force new URL 
     iFrame.attr('src', newSrc); //changing the src triggers the load event 
    }); 

}); 

希望有帮助。

+0

如果我需要不同的处理程序进行加载和重新加载,该怎么办? – ZX12R 2010-09-28 10:36:55

+0

加载和重新加载在内部是一样的,你请求一个网页加载到一个iframe中,你可以做的是听第一个加载并在那里激发一个事件,如果是这样的话,让我知道,我会给你一个例子。问候。 – xmarcos 2010-09-28 15:39:08

+0

问题是这样的......最初当我给iframe分配一个src时,会附加一个加载事件...当我重新将url分配给iframe时,我附加了一个不同的加载事件处理程序......在重新分配第一个处理程序之后,不是第二个.. – ZX12R 2010-09-29 13:02:38

1

呃! javascript错误.. currentLocation未定义。在var currenctLocation

working demo

+0

对于错字感到抱歉...已经在小提琴中进行了更新..加载回调没有正常启动..http://jsfiddle.net/4tRWq/2/ – ZX12R 2010-09-28 07:27:35

+0

[demo](http:// jsfiddle.net/4tRWq/3/)< - 看演示。并尝试根据所做的警报来实现它。 – Reigel 2010-09-28 07:31:37

+0

你的问题是你的绑定'.load()'两次... – Reigel 2010-09-28 07:32:26