【发布时间】:2016-12-15 12:47:11
【问题描述】:
关于如何访问 iframe 中的全局变量,有人提出了几个问题。我想知道如何声明和初始化父级 iframe 范围内的全局变量。我知道我可以使用 document.myGlobalVariable 从 iframe 访问变量,但我希望能够通过说 myGlobalVariable 来引用它,而前面没有 document.。
这是我的 HTML:
<html>
<head>...</head>
<body>
...
<iframe src="myFrame.html"></iframe>
<script type="text/javascript">
var iframe = document.querySelector('iframe');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.myGlobalVariable = "Hello";
</script>
</body>
</html>
myFrame.html
<html>
<body>
...
<script type="text/javascript">
// wait for document to load so parent script can finish running
$(function() {
console.log(document.myGlobalVariable); // <-- This works
console.log(myGlobalVariable); // <-- But this doesn't (and I want this one)
});
</script>
</body>
</html>
谢谢!
【问题讨论】:
标签: javascript html iframe scope global-variables