gpt4 book ai didi

javascript - 从父级访问 iframe 的变量

转载 作者:IT王子 更新时间:2023-10-29 03:06:52 24 4
gpt4 key购买 nike

iframe脚本

<script type="text/javascript" >
var a=5;
</script>

父窗口脚本

<script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>

我想从父级访问在 iframe 中定义的变量。但是上面的代码不能正常工作,任何人都可以提出实现这个的想法。

最佳答案

使用 contentWindow 而不是 contentDocument 对我有用:

var check = document.getElementById("iframeid").contentWindow.a;

此外,请确保域匹配并且您正在使用网络服务器进行测试(我在从文件系统进行测试时收到协议(protocol)警告)。

更新:使用 postMessage API 几乎肯定会更好。

关于javascript - 从父级访问 iframe 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13757943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com