0

我正在动态创建一个IFrame然后向script它添加一个标签,其中包含在框架加载时应该执行的代码,但是它永远不会执行。

$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);

我假设window onload在将代码添加到IFrame. 无论如何要确保它被调用?此外,它需要包含在 in 中,window.onload因为它是基于 JS 的代码编辑器,因此 iframe 必须像在浏览器窗口中一样做出反应。干杯。

4

1 回答 1

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();
于 2011-01-20T07:54:30.923 回答