我想从父index.html访问iframe中的变量。

index.html:

<!doctype html>
<html lang="en-us">
  <head>
    <title>Test</title>
  </head>
  <body>
  <p>Test</p>
  <div>
  <iframe name="myIframe" id="test1" src="index2.html" width="100px" height="100px"></iframe>
  </div>
  <div>
    <script type="text/javascript">
        var clickParent = document.getElementById("test1").contentDocument.clicks;
        function onClickP() {
            console.log("click on parent: " + clickParent);
        };
    </script>
    <button type="button" onClick="onClickP()">Click Parent Button</button>
  </div>
  </body>
</html>


iframe index2.html:

<!doctype html>
<html>
<head>
    <title>Clicks</title>
</head>

<body>
    <script type="text/javascript">
    var clicks = 0;
    function onClick() {
        clicks += 1;
        console.log("click counts: " + clicks)
    };
    </script>
    <button type="button" onClick="onClick()">Click Child Button</button>
</body>
</html>


在控制台中,变量clickParent为“未定义”。如何解决此问题并使变量clickParent = clicks?

这个问题不是Sharing global javascript variable of a page with an iframe within that page的重复,因为相反。我想从父级访问iframe的变量,而不是从子级访问iframe的变量。我的问题是,父母从iframe访问的变量是“未定义”。

任何答案将不胜感激。谢谢。

最佳答案

可能是this的重复项。

在父级中声明全局变量,然后使用parent.var_name在iframe文档中进行设置。

您还可以通过为子文档创建一个对象来访问子var:

child_iframe = document.getElementById("iframe_id").contentWindow;
alert(child_iframe.var_name);

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

10-09 17:43
查看更多