2013-08-24 29 views
1

我在我的頁面中創建一個iframe這裏是它的代碼:負載事件不會在IE

var frame = document.createElement('iframe'); 
frame.setAttribute('src',''); 
document.body.appendChild(frame); 
if(document.addEventListener){ 
    frame.addEventListener('load', callback, false); 
} else { 
    frame.attachEvent('onload', callback); 
} 

function callback(){ 
    alert('test'); 
} 

它工作正常,在FF,但沒有在IE驚動的事,爲什麼呢?
請注意,我用IE10在Win8中

+0

什麼是控制檯輸出後移動到document.body.appendChild()? –

+0

@JeroenIngelbrecht我在IE控制檯中找不到任何東西! –

+0

attachEvent返回什麼?真假嗎? http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx –

回答

2

您需要addEventListener()電話

var frame = document.createElement('iframe'); 
frame.setAttribute('src',''); 
if(frame.addEventListener){ 
    frame.addEventListener('load', callback, true); 
} else { 
    frame.attachEvent('onload', callback); 
} 
document.body.appendChild(frame); 

function callback(){ 
    alert('test'); 
} 
+0

JS小提琴是[here](http://jsfiddle.net/MikeGodin/LX8qn/) –

+0

它的工作原理,但是當回調函數調用'frame.contentDocument.body'時是_null_,你能告訴我爲什麼嗎? –

+0

在此修訂的[jsfiddle](http://jsfiddle.net/LX8qn/2/)中,frame.contentDocument.body的值在Firefox,Chorme和IE 10中評估爲HTMLBodyElement對象。它看起來不是空值。 –