2013-06-03 60 views
0

我有一个带有两个iframe的网页:iframe.main和iframe.secondary。我想知道iframe.main中的页面被加载后,是否有方法将特定的页面加载到iframe.secondary?我会尽力来说明我想达到的目标:如何将两个单独的页面加载到两个单独的iframe?

<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> 

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

回答

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> 
+0

非常感谢!接下来我正在考虑以下内容:假设iframe.secondary会有一些默认页面,我们将其称为default.html。如何将iframe.secondary中加载的页面更改为default.html,因为我离开了iframe.main中的页面? – user2447547

+0

不确定你的意思是“将页面留在iframe.main”中。您可以将辅助iframe的初始'src'设置为“default.html”,并在加载“secondary.html”后添加另一个按钮以将其重新设置为“default.html”。对于更复杂的交互,我建议你看看jQuery或其他框架,因为普通的JavaScript往往会变得笨拙。 – kkoala

+0

另一个问题(对不起):如何将body onload事件设置为main.html,触发iframe.seconday中的secondary.html的加载?我试图找出如何去做,但没有成功...... – user2447547

相关问题