【问题标题】:Calling a javascript function in html page embedded in an object tag在嵌入对象标签的html页面中调用javascript函数
【发布时间】:2015-05-04 14:50:04
【问题描述】:

我有一个页面,其中包含嵌入在对象标记中的另一个页面。 现在我想从“父”页面调用一个 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 调用一个函数。 我怎样才能做到这一点?

谢谢你:)

【问题讨论】:

  • 您有问题要问或有问题要向我们展示吗?事实上,这更像是对您的状态的更新。
  • 抱歉不是问题
  • 提供一些代码来说明你的问题;此外,如果您可以发布迄今为止所做的工作以实现您期望的解决方案,那就更好了。
  • 对不起各位,昨天太累了,没意识到我在简单解释问题后忘记写问题了:) 希望你们能明白,我想做什么以及我的问题是什么。

标签: javascript html object-tag


【解决方案1】:

使用contentWindow 代替contentDocument 对我有用:

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

<script>
    var something = document.getElementById('childObject').contentWindow.getSomething();
</script>

【讨论】:

    【解决方案2】:

    你可以试试这个

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

    <script>
    var something = document.getElementById("childObject").parentElement.getSomething();
    </script>
    

    【讨论】:

    • 这不起作用,我认为这不是我真正想做的,因为我调用 .getSomething() 的 js 已加载到 parent.html 中,但感谢您的回复 :)
    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多