2011-01-20 83 views
0

我在動態創建IFrame,然後給它添加一個script標記,代碼應該在框架載入時執行,但它永遠不會執行。IFrame中的動態腳本沒有觸發window.onload

$stage.html("<iframe src='javascript:;' id='frame'></iframe>"); 
$frame = $("#frame"); 

frame = $frame[0].contentDocument ? $frame[0].contentDocument : $frame[0].contentWindow.document; 

script= frame.createElement('script'), 
head = frame.getElementsByTagName("head")[0]; 

script.innerHTML = "window.onload = function() { alert('loaded'); }"; 

head.appendChild(script); 

我假設的代碼添加到IFrame之前觸發事件window onload。無論如何要確保它被稱爲?它也需要包含在window.onload中,因爲它是基於JS的代碼編輯器,所以iframe必須像在瀏覽器窗口中那樣反應。乾杯。

+0

我認爲窗口已經加載,所以你的代碼錯過了onload事件。如果它尚未加載,則getElementsByTagName將失敗。雖然我不確定,但我沒有把它作爲正式答案 – qwertymk 2011-01-20 05:12:07

回答

2

通過使用window.write()解決。

frame = document.createElement("iframe"); 
frame.src = "javascript:;"; 
document.body.appendChild(frame); 

win = frame.contentWindow; 
win.document.open(); 
win.document.write(html); 
win.document.close();