最近因項(xiàng)目需求,需要在JS代碼中實(shí)現(xiàn)IFrame內(nèi)外頁(yè)面的互訪問(wèn)。經(jīng)過(guò)一番試驗(yàn)終于找到方法,以下是試驗(yàn)時(shí)用的代碼(在IE,F(xiàn)irefox中可正常運(yùn)行):
main.html
?1?<html>
?2?<head>
?3?????<title>MAIN</title>
?4?????<script?type="text/javascript">
?5???????? //?主頁(yè)面訪問(wèn)IFrame頁(yè)面DOM內(nèi)容
?6?????????function?oinit()?{
?7?????????????alert(getIFrameDoc("iframe1").getElementById("idiv").id);
?8?????????}
?9?????????function?getIFrameDoc(id)?{
10?????????????var?iframe?=?document.getElementById(id);
11?????????????var?doc?=?(iframe.contentWindow?||?iframe.contentDocument);
12?????????????if?(doc.document)?{
13?????????????????doc?=?doc.document;
14?????????????}
15?????????????return?doc;
16?????????}
17?????</script>
18?</head>
19?<body?onload="oinit()">
20?????<div?id="odiv">
21?????????<iframe?id="iframe1"?src="iframe.html"></iframe>
22?????</div>
23?</body>
24?</html>
iframe.html
?1?<html>
?2?<head>
?3?????<title>IFRAME</title>
?4?????<script?type="text/javascript">
?5???????? //?IFrame頁(yè)面訪問(wèn)外層頁(yè)面DOM內(nèi)容
?6?????????function?iinit()?{
?7?????????????alert(window.parent.document.getElementById("odiv").id);
?8?????????}
?9?????</script>
10?</head>
11?<body?onload="iinit()">
12?????<div?id="idiv">
13?</body>
14?</html>