如何将两个单独的页面加载到两个单独的iframe?

时间:2013-06-03 11:15:25

标签: iframe

我有一个包含两个iframe的网页:iframe.main和iframe.secondary。我想知道是否有办法将特定页面加载到iframe.secondary,因为iframe.main中的页面已加载?我将尝试说明我想要实现的目标:

<body>

 <iframe id="main" src="">

 </iframe>

 <iframe id="secondary" src="">

 </iframe>

 <button onClick="main.location.href='mainpage.html'">
  Load mainpage.html to iframe.main and secondary.html to iframe.secondary
 </button>

</body>

那么当mainpage.html加载到iframe.main时,如何将secondary.html加载到iframe.secondary?我可以使用按钮的onClick事件或mainpage.html的onLoad事件吗?

1 个答案:

答案 0 :(得分:0)

点击按钮更改/设置两个iframe的src属性。这是一个让您的HTML更精简的例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Two iframes</title>
<script type='text/javascript'>
window.onload = function(){
  // Get the button that will trigger the action
  var b = document.getElementById('trigger');
  // and set the onclick handler here instead of in HTML
  b.onclick = doLoads;

  // The callback function for the onclick handler above
  function doLoads() {
      // Get the two iframes
      var m = document.getElementById('main');
      var s = document.getElementById('secondary');
      // and set the source URLs
      m.src = "mainpage.html";
      s.src = "secondary.html";
  }

  // You could also move doLoads() code into an anonymous function like this:
  //     b.onclick = function () { var m = ... etc. }
} 
</script>
</head>
<body>
<iframe id="main" src=""></iframe>
<iframe id="secondary" src=""></iframe>
<br>
<button id="trigger">Load both pages</button>
</body>
</html>