从窗口向 iframe 传递值 [英] Pass value to iframe from a window

查看:9
本文介绍了从窗口向 iframe 传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向 iframe 发送一个值.

I need to send a value to an iframe.

iframe 存在于当前窗口中.我怎样才能做到这一点?

The iframe is present within the current window. How can I achieve this?

我需要在包含 iframe 的父窗口中使用 javascript 来完成.

I need to do it with javascript in the parent window that contains the iframe.

推荐答案

首先,你需要明白你有两个文档:框架和容器(包含框架).

First, you need to understand that you have two documents: The frame and the container (which contains the frame).

从容器操作框架的主要障碍是框架异步加载.您不能随时访问它,您必须知道它何时完成加载.所以你需要一个技巧.通常的解决方案是在框架中使用 window.parent 来向上"(进入包含 iframe 标签的文档).

The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent in the frame to get "up" (into the document which contains the iframe tag).

现在您可以调用容器文档中的任何方法.此方法可以操作框架(例如,使用您需要的参数在框架中调用一些 JavaScript ).要知道何时调用该方法,您有两种选择:

Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:

  1. 从框架的 body.onload 调用它.

  1. Call it from body.onload of the frame.

将脚本元素作为最后一件事放入框架的 HTML 内容中,您可以在其中调用容器的方法(留给读者作为练习).

Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).

所以框架看起来像这样:

So the frame looks like this:

<script>
function init() { window.parent.setUpFrame(); return true; }
function yourMethod(arg) { ... }
</script>
<body onload="init();">...</body>

容器是这样的:

<script>
function setUpFrame() { 
    var frame = window.frames['frame-id'];
    frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>

这篇关于从窗口向 iframe 传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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