操作iframe中的DOM元素

操作iframe中的DOM元素,有两个注意点:
1、必须先获取指定iframe的document;
2、对于1,必须在页面load完以后才能获取;

举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>操作iframe中的DOM元素</title>
<script type="text/javascript">
<!--
//返回指定iframe的document
function getIFrameDocument(aID) {
var rv = null;
if (document.getElementById(aID).contentWindow.document){
// if contentDocument exists, W3C compliant (Mozilla)
rv = document.getElementById(aID).contentWindow.document;
} else {
// IE
rv = document.frames[aID].document;
}
return rv;
}
function bindEvents() {
var iDocument = getIFrameDocument('test');
//接下来就可以进行类似的DOM操作了
var map = iDocument.getElementById('map');
//……
}
//-->
</script>
</head>
<body onload="bindEvents()">
<iframe id="test" name="giscontent" src="iframe.html" frameborder="0" scrolling="no">
</iframe>
</body>
</html>
显示 Gitment 评论