从另一个iframe更改iframe源代码

时间:2011-05-29 06:58:47

标签: javascript iframe

好的,我在父页面内有2个iframe(无论出于何种原因)。

我在父页面上有一个导航菜单,它改变了iframe#1 ...

的来源 iFrame#1的工作,是显示另一个导航菜单......就像一个子导航菜单...

现在,如何点击iFrame#1中的li,更改iframe#2的来源?他们都在同一个父页面上......

除了惨遭失败之外,我还会收到Chrome开发工具的警告 -

不安全的JavaScript尝试使用URL文件:/// C:/website/index.html从具有URL文件的框架访问框架:/// C:/website/news/navigator.html。域,协议和端口必须匹配。

这里有一些代码可以让事情变得更加清晰:

HTML

<!-- HTML for the parent page itself -->
<iframe id="frameone" src=""></iframe>
<iframe id="frametwo" src=""></iframe>
<button onclick="onenav('test.html')">Change 1st frame</button>

<!-- The following is the HTML that is loaded inside "frameone" -->
<button onclick="twonav('test2.html')">Change 2nd frame</button>

// Javascript
var one = document.getElementById('frameone');
var two = document.getElementById('frametwo');

function onenav(x){
    one.src = x;
}

function twonav(y){
    two.src = y;
}

对我而言,这是有道理的,因为这一切都在父页面上执行...在加载时,我查询开发工具,我可以看到,'one'和'two'都有框架元素..第一个按钮工作,第二个按钮不工作......

2 个答案:

答案 0 :(得分:5)

使用parent.twonav

时适合我

DEMO

var links = [
    'javascript:\'<button onclick="parent.twonav(1)">Change 2nd frame</button>\'',
    'javascript:\'Hello\''
];
var one, two;
window.onload=function() {
  one = document.getElementById('frameone');
  two = document.getElementById('frametwo');
}  

function onenav(idx) {
    one.src=links[idx];
}  

function twonav(idx) {
    two.src=links[idx];
}  

答案 1 :(得分:0)

您是如何尝试更改iframe来源的?

parent.document.getElementById('2').src = "the new url";
你试过这样的事吗?我从你的消息中假设第二个iframe的id是2。