问题描述
我需要向iframe发送一个值。
iframe存在于当前窗口中。我该如何做到这一点?
我需要在包含iframe的父窗口中使用javascript来完成它。
从容器操作框架的主要障碍是框架异步加载。你不能随时访问它,你必须知道它何时完成加载。所以你需要一个技巧。通常的解决方案是在框架中使用 window.parent
来获取up(包含 iframe
标签)。
现在您可以调用容器文档中的任何方法。此方法可以操纵框架(例如,使用您需要的参数在框架中调用一些JavaScript )。要知道何时调用该方法,您有两种选择:
-
从框架的body.onload调用它。
-
将脚本元素作为最后一件事放入框架的HTML内容中,在该框架中调用容器的方法(作为读者的练习留下)。
所以框架如下所示:
<脚本>
函数init(){window.parent.setUpFrame();返回true; }
函数yourMethod(arg){...}
< / script>
< body onload =init();> ...< / body>
而容器是这样的:
<脚本>
函数setUpFrame(){
var frame = window.frames ['frame-id'];
frame.yourMethod('hello');
}
< / script>
< body>< iframe name =frame-idsrc =...>< / iframe>< / body>
I need to send a value to an iframe.
The iframe is present within the current window. How can I achieve this?
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).
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).
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:
Call it from body.onload of the frame.
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>
And the container like this:
<script>
function setUpFrame() {
var frame = window.frames['frame-id'];
frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>
这篇关于将值从一个窗口传递给iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!