3

我有一个页面,其中包含嵌入在对象标签中的另一个页面。现在我想从“父”页面调用一个javascript函数。具体来说:父页面要调用一个函数,该函数位于嵌入代码中。以前我使用 iframe,但它们在 Firefox 中引起了一些讨厌的错误,所以我不想再使用它们了。

编辑:所以,我的问题是:使用对象标签时,实现这一目标的最佳方法是什么?

这里有一些例子来说明我想要做什么:

我在这个页面中有一个 HTML 页面“parent.html”,标签中有一些 Javascript。这个 parent.html 也有一个标签,这个标签的 src 是另一个 HTML 页面,我们称之为 child.html。child.html 页面具有以下内容:

这是一些伪代码:

在 Child.html 中:

<script type="text/javascript" src="child.js"></script>

在 Child.js 中:

function getSomething(){
    return something;
}

在 Parent.html 中:

<object id="childObject" data="child.html" width="850" height="510">
</object>

<script>
    // Here I want to access the function from the child.js
    // I tried something like this, but it doesn't work:
    var something = document.getElementById('childObject').contentDocument.getSomething();
</script>

现在:在 parent.html 内的 Javascript 中,我需要从 child.js 调用一个函数。我怎样才能做到这一点?

谢谢 :)

4

2 回答 2

1

使用contentWindow代替contentDocument对我有用:

<object id="childObject" data="child.html" width="850" height="510">
</object>

<script>
    var something = document.getElementById('childObject').contentWindow.getSomething();
</script>
于 2019-02-07T13:55:19.540 回答
0

你可以试试这个

<object id="childObject" data="child.html" width="850" height="510">

<script>
var something = document.getElementById("childObject").parentElement.getSomething();
</script>
于 2015-05-05T10:02:38.240 回答