[代码播放器]当 iframe 内容从文本区域使用 JavaScript 动态加载时,如何在 iframe 内查找元素
[codeplayer]How to find element inside of an iframe when the iframe content was dynamic loaded with javascript from a textarea
作为我的一个挑战,我决定做一个小的代码播放器,比如jsfiddle,我已经完成了所有的事情,但是当我尝试执行JS时,当我尝试像这样调用iframe中的元素时,我的问题来了:
document.getElementById("hola").innerHTML="nohola";
它只是说:
TypeError: document.getElementById(...) is null
有一个现场演示:jsfiddle.net
如何将 js 注入 iframe 并在其中调用元素?
问题是您的script
标签是由主文档的document
对象创建的。
var script = document.createElement('script');
这将使其中的 javascript 范围限定为主文档。你必须使用iframe
的document
对象来创建它,以便javascript的范围将限定为iframe
。
可以通过 contentWindow.document
属性访问iframe
文档,如下所示:
检查这个小提琴
function runJs() {
var iframe = document.getElementById('resultIframe');
var frameDoc = iframe.contentDocument || iframe.contentWindow.document;
var body = $('body', frameDoc);
var code = $('#codeJs').find('textarea').val();
var script = frameDoc.createElement("script"); // not document.createElement('script');
script.setAttribute("type", "text/javascript");
script.textContent = code;
body[0].appendChild(script);
}
另请参阅这些答案
来自 iframe 的 getElementById
在 iframe 的本地范围内注入 JavaScript
相关文章:
- 如何在iFrame中触发iFrame加载
- 在iframe加载后删除类
- BrowserAction.onClicked等待iframe加载
- Iframe加载调整大小在Chrome中工作,但不能在IE或Firefox中工作
- Dojo:在 iframe 加载时解析 HTML 内容
- Iframe 加载回调被多次调用
- 阻止iframe加载到移动设备上
- 如何将隐藏/显示事件延迟到提交后Iframe加载
- Iframe加载动画不起作用
- iframe 加载事件中的 setTimeout 似乎没有像预期的那样等待 x 秒
- 强制同步 iframe 加载
- 如何javascript调用iframe加载的文件函数
- 显示微调器,直到 iframe 加载 http post 响应
- 在 KnockoutJS 应用程序中将 AngularJS 应用程序作为 iFrame 加载
- 如何捕获 iframe 加载错误
- 在执行函数之前等待多个 iFrame 加载
- JavaScript 在 Iframe 加载时显示加载 gif
- 如何使 iFrame 在 iframe 加载特定页面时重新加载它所在的页面
- 要随索引页一起加载的滚动更新,并在 iframe 加载来自链接的内容时消失
- 一个页面上有多个 Iframe 加载问题