在iframe中调用javascript函数 [英] Calling javascript function in iframe

查看:121
本文介绍了在iframe中调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从父页面调用 iframe 中的JavaScript函数时遇到问题。这是我的两页:

I have problem calling a JavaScript function in an iframe from the parent page. Here is my two pages:

mainPage.html

<html>
<head>
    <title>MainPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            if (document.all.resultFrame)
                alert("resultFrame found");
            else
                alert("resultFrame NOT found");

            if (typeof (document.all.resultFrame.Reset) == "function")
                document.all.resultFrame.Reset();
            else
                alert("resultFrame.Reset NOT found");
        }
    </script>
</head>
<body>
    MainPage<br>
    <input type="button" onclick="Reset()" value="Reset"><br><br>
    <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe>
</body>
</html>

resultFrame.html

<html>
<head>
    <title>ResultPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            alert("reset (in resultframe)");
        }
    </script>
</head>
<body>
    ResultPage
</body>
</html>

(我知道 document.all isn不推荐,但这个页面只能在内部用IE查看,我不认为这是问题。

(I know that document.all isn't recommended but this page should only be viewed with IE internally and I don't think that's the problem)

当我按下重置按钮时,我得到resultFrame found 和resultFrame.Reset NOT found。它似乎有一个框架的引用但不能调用框架上的函数,为什么会这样?

When I press the Reset-button I get "resultFrame found" and "resultFrame.Reset NOT found". It seems to have a reference to the frame but can't call the function on the frame, why is that?

推荐答案

使用:

document.getElementById("resultFrame").contentWindow.Reset();

访问iframe中的重置功能

to access the Reset function in the iframe

document.getElementById(resultFrame)
将获取代码中的iframe, contentWindow 将获取iframe中的窗口对象。拥有子窗口后,您可以在该上下文中引用javascript。

document.getElementById("resultFrame") will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

另请参阅 HERE ,特别是来自bobince的答案。

Also see HERE in particular the answer from bobince.

这篇关于在iframe中调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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