从iframe外部调用javascript函数 [英] call javascript function from outside an iframe

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

问题描述

我在包含javascript函数getData()的iframe中有一个完整的html openning。现在我不知道如何从该框架外部调用getData()。还可以从外部javascript文件中调用它吗?

I have one entire html openning inside an iframe that contains a javascript function getData().Now I am not sure how to call getData() from outside that frame.Also is it possible to call it from an external javascript file ?

推荐答案

您可以从window.frames属性获取对框架窗口对象的引用。请参见 https://developer.mozilla.org/en/DOM/window.frames

You can get a reference to the frame window object from the window.frames property. See https://developer.mozilla.org/en/DOM/window.frames

更新:

您可以访问命名iframe的全局上下文使用窗口[framename] 。例如:

You can access the global context of a named iframe with window[framename]. e.g:

<iframe src="data.html" name="data"></iframe>

<script>
var myData = window.data.getData();
</script>

虽然您需要确保iframe已加载。

Although you will need to make sure the iframe has loaded.

在jQuery中,如果要访问iframe DOM,可以使用contents方法:

In jQuery you can use the contents method if you want access to the iframe DOM:

$("iframe").contents()

所有这一切都假设框架在同一域名

All this is assuming the frame hosted within the same domain.

更新[2]:

您询问是否可以从外部js文件调用 getData 函数。答案是肯定的(如果我理解正确的话)。以下是一个示例:

You asked if it is possible to call the getData function from an external js file. The answer is yes (if I understand you correctly). Here is an example:

<html>
<head>
    <meta charset="utf-8">
    <title>parent page</title>
</head>
<body>

    <iframe src="data.html" name="data"></iframe>
    <script src="getdata.js"></script>

</body>
</html>

然后在 getdata.js 文件中拥有:

var dataFrame = window.data;

// when the frame has loaded then call getData()
dataFrame.onload = function () {
    var myData = dataFrame.getData();
    // do something with myData..
}

希望这能回答你的问题问题:)

Hope this answers your question :)

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

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