JavaScript/JQuery向嵌套iframe写入内容时遇‘doc.open不是函数’错误
问题分析与解决方案
首先明确说:向嵌套iframe写入内容是完全支持的,你的代码思路是对的,只是在获取内层post iframe的document对象时犯了个小错误,导致了doc.open is not a function的报错。
错误原因
在第二个循环里,你通过document.getElementById('trial'+index).contentWindow.document.getElementById('post'+i)获取到的是post iframe这个DOM元素本身,而不是它内部的文档对象(contentWindow.document)。普通的iframe DOM元素并没有open()方法,这就是报错的根源。
修正后的代码
下面是调整后的可运行代码,关键修改点已经标注:
<div id="exp_div"></div> <script> procedure = [ [ "content 1","content 2" ] ] procedure.forEach(function(this_proc,index){ $("#exp_div").append("<iframe id='trial"+index+"' width='800px' height='800px'></iframe>"); trial_iframe_code = ''; for(var i = 0; i < this_proc.length; i++){ trial_iframe_code += "<iframe id='post"+i+"'></iframe>"; } // 获取trial iframe的document const trialDoc = document.getElementById('trial'+index).contentWindow.document; trialDoc.open(); trialDoc.write(trial_iframe_code); trialDoc.close(); for(var i = 0; i < this_proc.length; i++){ const trialContent = this_proc[i]; // 关键修改:先拿到post iframe元素,再获取它的contentWindow.document const postIframe = trialDoc.getElementById('post'+i); const postDoc = postIframe.contentWindow.document; postDoc.open(); postDoc.write(trialContent); postDoc.close(); } }) </script>
关键修改说明
- 给变量起了更清晰的名字(比如
trialDoc、postIframe、postDoc),避免重复获取元素,也更易读。 - 在第二个循环中,先拿到post iframe的DOM元素,再通过
contentWindow.document获取它内部的文档对象,之后再调用open()/write()/close()就没问题了。 - 复用了之前获取的
trialDoc,不用再重复从外层获取,提升效率。
额外建议
如果你的实验需要更复杂的内容,或者担心iframe加载时序问题,可以考虑:
- 给内层iframe添加
load事件监听,确保在它加载完成后再写入内容(不过当前同步写入的场景下不需要)。 - 尽量减少嵌套iframe的层级,过多的嵌套可能会带来调试和性能上的小问题,如果可以用div等元素模拟的话,会更轻便。
内容的提问来源于stack exchange,提问作者beepingbopping
相关产品推荐
相关产品推荐

