javascript - 是否可以访问 iframe 之外的数组?
问题描述
问题是这样的:在我的主页 ( parent.html
) 内,我有一个 iframe ( child.html
) 和一个脚本块。在该脚本块中有一个整数数组和一个将元素添加到列表的函数。在 iframe 中有一个新函数,可以将元素添加到主文件 ( parent.html
) 的列表中。
我想知道 iframe( child.html
) 是否可以访问parent.html
. 例子:
父.html
<html>
<head>
<title>Parent</title>
<script>
var parentList = [0];
var counter = 0;
function addValue(){
counter++;
parentList.push(counter);
console.log('parent', parentList);
}
</script>
</head>
<body>
<button onclick="addValue()">Add Value (Parent)</button>
<br />
<iframe src="child.html" allowfullscreen></iframe>
</body>
</html>
child.html
<html>
<head>
<title>Child</title>
</head>
<body>
<button onclick="addValueInternal()">Add Value Child</button>
<script>
var internalCount = 0;
function addValueInternal() {
internalCount++;
parentList.push(internalCount);
console.log('child', parentList);
}
</script>
</body>
</html>
错误:
child.html:12 Uncaught ReferenceError: parentList is not defined
at addValueInternal (child.html:12)
at HTMLButtonElement.onclick (child.html:6)
解决方案
是的。有可能的。基于从嵌入式 iframe 调用父级中定义的函数的示例。
因此,在您的情况下,您必须parent
在访问数组时引用。
function addValueInternal() {
internalCount++;
parent.parentList.push(internalCount); // here we access the reference
console.log('child', parentList);
}
请注意,您之后可能会遇到有关跨域策略的问题。
推荐阅读
- python - Python 正则表达式将日期提取到数据框中的新列
- c - NPTL 中的线程如何退出?
- reactjs - 反应组件中的问题
- r - 用R中的data.table中的0替换所有NA
- javascript - 从 JavaScript 中的多维数组对象中获取唯一值
- reactjs - 不推荐使用 findDOMNode 并切换到 forwardRef() 的反应抛出问题
- python - 网页抓取时过滤掉标签的最佳方法?
- android - Firebase 无法从控制台编辑 android 应用程序的动态链接行为
- javascript - SplideJS 滑块 - 如果数组的最后一个或第一个幻灯片项返回空错误
- cakephp - CakePHP 4 CMS 身份验证教程重定向到登录不起作用(忽略子文件夹)