是否可以访问 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>

孩子.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)


天涯尽头无女友
浏览 58回答 1
1回答

蛊毒传说

是的。有可能的。因此,在您的情况下,您必须parent在访问数组时引用 。function addValueInternal() {  internalCount++;  parent.parentList.push(internalCount); // here we access the reference  console.log('child', parentList);}请注意,之后您可能会遇到有关跨域策略的问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5