js中window.top, self, parent之间的关系

项目场景:

准备3个html页面,层级结构是 a.html <= b.html , <= c.html
a.html是最顶层父页面


问题描述:

a.html 中引入 b.html

<body>
  <iframe src="./b.html" frameborder="0" class="son" id="son1"></iframe>
</body>

a.html中定义变量aaaa=1

<script type="text/javascript">
  window.aaaa = 1
  console.log(top);
  console.log(window);
  console.log(window.top);
  console.log(window.self);
  console.log(window.parent);
  console.log(parent);
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

b.html 中引入 c.html

<body>
  <iframe src="./c.html" frameborder="0" class="son" id="son2"></iframe>
</body>

b.html中定义变量aaaa=2

<script type="text/javascript">
  window.aaaa = 2
  console.log(top);
  console.log(window);
  console.log(window.top);
  console.log(window.self);
  console.log(window.parent);
  console.log(parent);
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

c.html 中定义变量aaaa=3

<script type="text/javascript">
  window.aaaa = 3
  console.log(top);
  console.log(window);
  console.log(window.top);
  console.log(window.self);
  console.log(window.parent);
  console.log(parent);
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

最终输出结果:

a.html

<script type="text/javascript">
  window.aaaa = 1
  console.log(top);    //aaaa = 1
  console.log(window);    //aaaa = 1
  console.log(window.top);    //aaaa = 1
  console.log(window.self);    //aaaa = 1
  console.log(window.parent);    //aaaa = 1
  console.log(parent);    //aaaa = 1
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

在最顶层a.html中 所有window对象中顶层的aaaa都等于1

b.html

<script type="text/javascript">
  window.aaaa = 2
  console.log(top);    //aaaa = 1
  console.log(window);    //aaaa = 2
  console.log(window.top);    //aaaa = 1
  console.log(window.self);    //aaaa = 2
  console.log(window.parent);    //aaaa = 1
  console.log(parent);    //aaaa = 1
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

b.html中 单独window对象window.self指向了b.html本身的window 对象,其余的top parent指向了父级window

c.html

<script type="text/javascript">
  window.aaaa = 3
  console.log(top);    //aaaa = 1
  console.log(window);    //aaaa = 3
  console.log(window.top);    //aaaa = 1
  console.log(window.self);    //aaaa = 3
  console.log(window.parent);    //aaaa = 2
  console.log(parent);    //aaaa = 2
  console.log("-=-=-=-=-=-=-=-=-=-=-=-=");
</script>

c.html中 单独window对象window.self 依然指向了c.html本身的window 对象。
topwindow.top 指向了最顶层的a.html
window.parent parent指向了b.html


所有在iframe中,
windowwindow.self 最终都是指向自己本身拥有的window
topwindow.top 都是指向最顶层的window,最开始的window。
parentwindow.parent 指向本级window父window不会指向最开始的祖先window


微信群大佬都在等着你

微信扫描二维码加入微信群,交流学习,及时获取代码最新动态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值