如何访问iframe的$(document).ready(function(){})中包含的函数? [英] How can I access the functions wrapped in the $(document).ready(function(){}) of an iframe?

查看:161
本文介绍了如何访问iframe的$(document).ready(function(){})中包含的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个iframe,它有一些函数包含在$(document).ready(function(){})中。

So I have an iframe that has some functions wrapped in a $(document).ready(function(){}) like this.

<script>
    $(document).ready(function(){
        function foo(){
            // do some stuff
        }
    });
</script>

我知道我可以使用类似$('iframe')的东西访问DOM。内容() .find('something'),但是我可以从上面访问foo()函数吗?

I know that I can access the DOM with something like $('iframe').contents().find('something'), but can I access the foo() function from above?

推荐答案

你无法访问变量在iframe的ready函数中出于同样的原因,你无法访问任何其他函数的局部变量(你不能在范围内向下)。但是,如果您可以修改iframe中的代码,则可以随时进入范围。所以在你的iframe代码中:

You cannot access the variables in that ready function of the iframe for the same reason that you cannot access local variables of any other function (you can't "go down" in scope). If you can modify the code in the iframe, however, you can always go up in scope. So in your iframe code:

$(document).ready(function() {
    function func1() {
        alert("Function in iframe");
    }

    parent.iframeFunctions = {
        test: func1
    }
});

下一个问题是您需要能够访问该功能。您无法使用正常的jquery文档,因为当父页面的DOM准备就绪时iframe未完成加载,因此在父页面中仍未定义iframeFunctions对象。你需要这个:

The next problem is that you need to be able to access the function. You cannot use the normal jquery document ready, because the iframe is not finished loading when the parent page's DOM is ready and therefore your iframeFunctions object is still undefined in the parent page. You need this:

$(window).load(function() {
    iframeFunctions.test();
});

但是,您可以访问iframe的全局空间。哦是的,到目前为止,这都是假设iframe源属于同一域策略。如果没有,那么涉及的工作量就会增加很多,而且在很多情况下甚至都不值得。例如,jquery对象位于全局空间中,所以这里是你如何得到iframe的jquery:

You can, however, access the global space of the iframe. Oh yeah, so far this is all assuming that the iframe source falls within the same domain policy. If not, there's a lot more work involved, and in a lot of cases it's not even worth it. The jquery object, for example, is in the global space, so here's how you get at the iframe's jquery:

$("iframe")[0].contentWindow.$("#divInIframe")

所以,如果你修改了使用函数表达式而不是函数声明的iframe源代码的内容:

So, if you modified the content of the iframe source to use function expressions rather than function declartions:

var func1 = function() {
    alert("Function in iframe");
}

$(document).ready(function() {
    func1();
});

您也可以从父母访问它(在窗口加载事件触发后) ):

You'd be able to access it from the parent as well (after the window load event has fired):

$(window).load(function() {
    $("iframe")[0].contentWindow.func1();
});

这篇关于如何访问iframe的$(document).ready(function(){})中包含的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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