1

test在我的test.html. 该 iframe 中加载了另一个test2.html文件test,我需要访问在test2.html. 有什么办法可以在test.html.

这是我的样品

测试.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Styles/redmond/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <script src="Js/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
           //this code is doesn't work
           var data1= document.getElementById('test').contentWindow.document.data;
        });
    </script>
    <style type="text/css">
        body,html{
            height:100%;
            width:100%;
            top:0;
            left:0;
            overflow:auto;
        }
        #test{
            height:250px;
            width:250px;
            border:1px solid gray;
        }
    </style>
</head>
<body>
    <iframe id="test" src="test2.html"></iframe>
</body>
</html>

test2.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Styles/redmond/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <script src="Js/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <script type="text/javascript">
        var data = 'This data is retrived from test2.html';
        $(document).ready(function () {
            $('#div')[0].textContent = data;
        });
    </script>
    <style type="text/css">
        body,html{
            height:100%;
            width:100%;
            top:0;
            left:0;
            overflow:auto;
        }
        #div{
            height:50px;
            width:200px;
            border:1px solid gray;
            margin:10px;
        }
    </style>
</head>
<body>
    <div id="div">Hello</div>
</body>
</html>

任何建议都应该不胜感激......!

4

1 回答 1

1

如前所述,您应该从中获取变量,contentWindow而不是contentWindow.document. 而且,您可能需要等待 iframe 加载。

$(document).ready(function(){
     $('#test').on('load',function(){           
          var data1 = $('#test').get(0).contentWindow.data;
          // Or plain JavaScript
          // var data1 = document.getElementById('test').contentWindow.data;
     });
});
于 2013-09-11T09:41:16.663 回答