[英]Accessing JavaScript variable in an iframe, from the parent window on same domain
I am fairly new to JavaScript and I am trying to get value of a variable from an embedded iframe. 我对JavaScript很新,我试图从嵌入式iframe中获取变量的值。 I have resorted to basic testing to make sure I am getting the method right... 我已经采取了基本的测试,以确保我正确的方法...
I have tried the common suggestions and everything returns 'undefined'. 我尝试了常见的建议,一切都返回'undefined'。 I want to use the variable in an onclick event. 我想在onclick事件中使用该变量。
In the iframe content I have stripped everything and just for testing have this: 在iframe内容中,我删除了所有内容,只是为了进行测试而已:
<script>
var test = "test";
</script>
in the parent window I have done this: 在父窗口中我做了这个:
<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>
<script>
var myVar = window.frames[0].window.test;
</script>
<a href="#" onclick='alert(myVar)' id="link">Click</a>
I have tried the options suggested here: grab global variable from an embedded iframe 我已经尝试了这里建议的选项: 从嵌入式iframe中获取全局变量
Everything I do returns undefined... am I doing something fundamentally wrong? 我所做的一切都是未定义的......我在做一些根本错误的事情吗?
Thanks in advance.. 提前致谢..
You are already executing the script when the <iframe>
is still loading, so it's test
is undefined
. 当<iframe>
仍在加载时,您已经在执行脚本,因此它的test
undefined
。 Either wait for the iframe's load
event, or just get the variable when clicking: 要么等待iframe的load
事件,要么在单击时获取变量:
<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>
<script>
var myFrame = window.frames[0].window;
</script>
<a href="#" onclick='alert(myFrame.test)' id="link">Click</a>
You're apparently not waiting for the frame's content to be loaded before accessing myVar
. 在访问myVar
之前,您显然没有等待加载帧的内容。 Chances are the <script>
element in the frame has not yet been fetched or executed when you do that. 当你这样做时,框架中的<script>
元素尚未被提取或执行。
Try delaying the variable assignment until the frame's content is fully loaded: 尝试延迟变量赋值,直到帧的内容完全加载为止:
<iframe src="iframe.html" id="iframe" onload="frameLoaded();" width="200" height="100"></iframe>
<script>
var myVar;
function frameLoaded() {
myVar = window.frames[0].window.test;
}
</script>
As an aside, since your question is tagged jquery I would suggest you write something like: 顺便说一句,既然你的问题被标记为jquery,我建议你写一些类似的东西:
<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>
<script>
$("#iframe").on("load", function() {
var myVar = this.window.test;
$("#link").on("click", function() {
alert(myVar);
});
});
</script>
try to use this 试着用这个
<iframe src="iframe.html" id="iframe" onload="loader()" width="200" height="100"> </iframe>
<script>
var myVar
function loader(){
myVar = window.frames[0].window.test;
}
</script>
<a href="#" onclick='alert(myVar)' id="link">Click</a>
在旁边的解决方案中,我只想指出当你使用jquery onload事件处理函数并且你想要访问jquery“this”对象时,你必须使用$(this.attr)表示法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.