动态加载到iframe中的JavaScript在父范围内运行 [英] JavaScript dynamically loaded into iframe runs in parent scope

查看:226
本文介绍了动态加载到iframe中的JavaScript在父范围内运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iframe,并使用以下代码将html + javascript动态加载到其中:

I have an iframe and I load some html+javascript into it dynamically with the following code:

var allMyCode = "<div id='test'>html code</div> <script type='text/javascript'>alert(document.getElementById('test').innerHTML);<\/script>";
$("#myFrame").contents().find("body").html(allMyCode);

问题是我想向文本"html代码"发出警报,但实际上它是在id为"test"的父级的div中获取html,因此它不是在引用自身.我已经在这个小提琴中显示了此内容: http://jsfiddle.net/BNG4n/

The problem is I would like this to alert the text 'html code' but it actually gets the html in the div in the parent with the id of 'test', so it's not referencing itself. I've shown this in this fiddle: http://jsfiddle.net/BNG4n/

为什么这样做,如何使JavaScript在自己的作用域上运行!?

Why is it doing this, how can I make the JavaScript run on its own scope!?

推荐答案

因为jQuery在设置iframe的body元素的html之前执行脚本元素,该html元素始终在父范围内.

Because jQuery executes the script element before setting the html of the iframe's body element which will always be in parent scope.

您可以尝试创建一个脚本元素,并将其添加到iframe的正文中,即可按预期工作.

You can try to create a script element and append inside iframe's body it will work as expected.

类似这样的东西.

var allMyCode = "<div id='test'>html code</div>";
$("#myFrame").contents().find("body").html(allMyCode);
var el = document.createElement("script");
el.setAttribute("type","text/javascript");
el.innerHTML = "alert(document.getElementById('test').innerHTML);";
$("#myFrame").contents().find("body")[0].appendChild(el);

工作演示- http://jsfiddle.net/BNG4n/1/

这篇关于动态加载到iframe中的JavaScript在父范围内运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆