您的位置:首页 > Web前端 > JavaScript

js:iframe的使用及页面嵌套多个iframe时iframe和父页子页之间的调用

2018-01-26 11:30 274 查看
首先,iframe引入的页面是一块独立的内存 意思就是 这个页面的元素、js等不会和他的上下页共享

新建html文件a.html、b.html、c.html。a.html代码如下

<div class="tabcont" id="menutab_1_1" style="height:600px">
<iframe align="center" width="100%" src="b.html"  frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div>
<div class="tabcont" id="menutab_1_2" style="display:none;height:600px;">
<iframe align="center" id="dealIframe" name="dealIframe" width="100%" src="c.html"  frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div>

如上在a.html中定义了两个iframe分别引入了b.html和c.html a页包含了b和c页

接下来我们在a、b、c三个页面中分别加入一个同名的input元素 如下代码

<input name="testLength" type="hidden"/>

并在3个页面的js中打印testLength的个数



结果:
a页面的num为0

b页面的num为1

c页面的num为1

可见 每个ireame的内存是独立的 他们之间的元素互相也不会冲突

冲突的问题解决了 那么要是调用其他页面的函数或者元素该怎么办呢?


//在b页获取c页元素

parent.window.frames["dealIframe"].window.document.getElementsByName("testLength");//javascript写法

$("[name='testLength']",parent.window.frames["dealIframe"].window.document);//jquery写法


在a页中定义函数testFun
//在b页刷新c页的方法
parent.window.frames["dealIframe"].window.location.reload();
//在b页调用a页面testFun方法
window.parent.window.testFun;//调用方式1
parent.testFun;//调用方式2

关于window对象
window 当前页

window.document document是window的一个对象
表示当前页的文档内容

 window.top

 功能:返回顶层窗口,即浏览器窗口。
 window.parent
 功能:返回父窗口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息