我有一個輸入,它有一個動態值,因爲它是可編輯的。 Onkeypress在textarea或之後onclick點擊btn id時觸發事件,它應該在另一個iframe上添加輸入值,因爲輸入是可更改的,所以它是動態的。因此,如果沒有頁面加載,iframe的腳本innerHTML應該刷新。我做了一些事情,但沒有成功。我想動態追加腳本在onclick或onkeypress事件觸發後的iframe
HTML
<textarea id="inpt" cols="30" rows="10"></textarea>
<div><input type="submit" value="append" id="btn" style="width:60px;height:20px;background:grey"></div><br>
<iframe id="fr" name="fr" style="width:300px;height:300px;"></iframe>
JS
var _script = document.createElement('script');
_script.type = 'text/javascript';
var iFrame = document.getElementById('fr'),
iFrameBody,
t = document.getElementById("inpt"),
btn = document.getElementById('btn');
function injectJS(content, val) {
if (iFrame.contentDocument)
{
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if (iFrame.contentWindow)
{
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
iFrameBody.appendChild(content);
content.innerHTML = val;
console.log(iFrameBody);
}
//t.onkeypress = injectJS(_script, t.value);
btn.onclick = injectJS(_script, t.value);
而這裏的工作演示。 http://jsfiddle.net/n5fdywb9/
參見另一篇文章(http://stackoverflow.com/questions/86428/whats-the-best-way-to-reload-an-iframe-using-javascript)我看到訪問框架的內容是這樣的:「document.getElementById('some_frame_id')。contentWindow」。所以你可能也可以這樣訪問文檔。 – 2014-10-09 10:05:03
@PeterBranforn我也試過這個,因爲我在其他地方使用,如果在這裏檢查,但沒有運氣。 – 2014-10-09 10:10:09