如何使用javascript从iframe打开链接

时间:2011-08-28 16:32:27

标签: javascript iframe href

我有这个:

<td onclick="window.location='http://www.google.com/';"> </td>

问题是我在iframe中有这个,所以点击它在iframe中打开。如何在父页面而不是iframe上打开此链接?

(有没有办法用一个js脚本为页面上的所有链接做这个?)

2 个答案:

答案 0 :(得分:4)

window.parent.location.href='http://www.google.com/';

如果你想重新加载最顶层的窗口:

window.top.location.href='http://www.google.com/';

答案 1 :(得分:1)

使用js脚本对页面上的所有链接执行此操作的一种方法是在加载页面时在链接上添加onClick事件。这是一个快速代码。将此代码放在一个文件中并将其放在iframe中。

<html>
<script>
function openInParent() {
  window.parent.location = this.href;
  return false;
}

function doload () {
  // loop through all links in the page to add onclick event
  var links = document.getElementsByTagName ('a');
  for(i in links) {
    links[i].onclick = openInParent;
  }
}

window.onload = doload;
</script>
<body>
<a href="http://www.google.com">test</a>
</body>
</html>