父级:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="js/jquery-1.11.3.js"></script>
<style>
* {padding: 0; margin: 0;}
body,html {width: 100%; height: 100%;}
</style>
</head>
<body>
<iframe id="qq" name="myFrame" src="test2.html" frameborder="0"></iframe>
</body>
<script>
;$(function() {
var x = document.getElementById('qq').contentWindow.document.getElementById('div1');
console.log(x);
});
</script>
</html>
子级:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="js/jquery-1.11.3.js"></script>
<style>
* {padding: 0; margin: 0;}
body,html {width: 100%; height: 100%;}
#div1 {height: 200px; background: red;}
</style>
</head>
<body>
<div id="div1">123</div>
</body>
<script>
$(function() {
})
</script>
</html>
请问为什么输出的null???
我想操作iframe里面的元素,求解决?
如果换成:
var x = $(window.frames["myFrame"].document).find("#div1").text();
console.log(x);
输出的是空值,不知道问题到底出在哪里??网上教程对不对啊
http://blog.jjonline.cn/userInterFace/140.html
$(function(){...})是父页dom对象好了就执行,iframe不一定加载完毕,改为$(window).load
$(window).load(function() {
var x = document.getElementById('qq').contentWindow.document.getElementById('div1');
console.log(x);
});
父级页面js:
function getChildEle() {```
var x = document.getElementById('qq').contentWindow.document.getElementById('div1');
console.log(x);
}
子级页面JS:
$(function() {
window.top.getChildEle();
});
父级页面js:
function getChildEle() {```
var x = document.getElementById('qq').contentWindow.document.getElementById('div1');
console.log(x);
}
子级页面JS:
$(function() {
window.top.getChildEle();
});
var x = $('#div1', window.iframes['iframename'].document)
你酱紫肯定要失败了,浏览器是有安全性约束的,如果在一个A域的页面内嵌一个B域的,而且A还要通过代码去访问B的内容,这就是所谓的XSS(Cross Site Script)夸域攻击了。