我在test
中使用iframe test.html
。在iframe test2.html
中加载了另一个test
文件,我需要访问test2.html
中使用的变量。有没有办法在test.html
中访问它。
这是我的样品
的test.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>
任何建议都应该受到赞赏......!
答案 0 :(得分: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;
});
});