1

考虑以下三页。

  1. Foo.html在浏览器中本地打开,因此有一个带有前缀的 URL file:///
  2. Bar.html是在同一个目录下Foo.html
  3. Bar2.html住在里面,/var/www我正在Apache继续localhost

Foo.html

<html>
  <head>
  <script>
  foo = function() {
    alert("frame changed");
  };
  </script>
  </head>

  <body>
  <iframe width="200" height="300" src="Bar.html" id="my-iframe" onLoad="foo" /> 
  </body>
</html>

酒吧.html

<html>
  <body>
  <iframe width="200" height="300" src="http://localhost/Bar2.html" id="my-iframe" /> 
  </body>
</html>

Bar2.html

<html>
  <head>
  <script>
  if (top.location != self.location){
      parent.location = self.location;
  }
  </script>
  </head>
  <body>
  <button type="button" onclick="document.location.href='http://bing.com'">Hello World</button>
  </body>
</html>

Foo.html在 Firefox 中加载时,通过firefox /path/to/Foo.html在命令行上运行,框架破坏代码中Bar2.htmlBar.html. 此时,用户会收到警报frame changed

当我单击按钮时,iframe更改(按钮消失),但我没有收到警报。

为什么onLoad页面更改时第二次不触发?

4

2 回答 2

1

问题在于,当 Bar2.html 由 Bar.html 中的 iframe 加载时,此条件为假

if (top.location != self.location)

结果,当 Bar.html 加载 Bar2.html 时,这被称为

parent.location = self.location;

它在页面中发出重定向并取消 onload 事件的影响,因为页面在技术上从未完成加载。

于 2014-05-05T23:21:42.813 回答
0

你的脚本

  if (top.location != self.location){
      parent.location = self.location;
  }

将在 Bar2.htm 上运行并更改其父级(以前为 Bar.htm)的位置。然后警报来了。然后,脚本将在父级(以前的 Bar.htm)中运行,但 top.location 仍然不等于 self.location。(top.location 现在等于 Foo.htm 并且 self.location 等于 Bar.htm )所以当您单击按钮时,父页面已被重定向到 Bar2.htm 。意味着警报代码和 iframe 消失了。

于 2014-05-05T23:00:38.557 回答