使用 javascript 更改 iframe 中的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7036572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change URL in an iframe using javascript
提问by Dave Smith
I have a in an iframe, that calls a function from the parent page. The function is window.location, however this does not change the url. Is there a way to have the iframe call a function from the parent page, that will cause the iframe to change url? I also had a basic qustion, if I have an iframe, and click on a link that brings me to a new page, does the parent page remain open?
我在 iframe 中有一个,它从父页面调用一个函数。函数是window.location,但这不会改变url。有没有办法让 iframe 从父页面调用一个函数,这会导致 iframe 更改 url?我也有一个基本问题,如果我有一个 iframe,然后单击一个将我带到新页面的链接,父页面是否保持打开状态?
Thanks in advance for your help. Sorry if I sound like a complete idiot, I am new to javascript.
在此先感谢您的帮助。对不起,如果我听起来像个彻头彻尾的白痴,我是 javascript 新手。
Dave
戴夫
回答by Christian
window.location
is not a function, it s an object.
window.location
不是函数,它是一个对象。
To do what you want, first make the iframe call a special function from it's parent.
为了做你想做的事,首先让 iframe 从它的父级调用一个特殊的函数。
parent.sendMeToGoogle();
And in the function (in parent) do something like:
并在函数中(在父级中)执行以下操作:
function sendMeToGoogle(){
document.getElementById('iframeID').src="http://google.com/";
}
回答by LaPuyaLoca
If what you really need is to change the parent URL, you can use window.top.location.href='http://anotherURL.com'
even if they are in different domains, from the iframe page.
如果您真正需要的是更改父 URL,window.top.location.href='http://anotherURL.com'
即使它们位于不同的域中,您也可以从 iframe 页面使用。
回答by Steven
I assume that you want to do more in the function of your parent page; if not you can just change the url of the iframe without calling the parent of course...
我假设您想在父页面的功能上做更多的事情;如果不是,你当然可以只更改 iframe 的 url 而不调用父级......
As for your second question, the iframe behaves like an ebmedded page: you can browse all you want in the iframe without affecting the parent (except of course with javascript calls like the one you want to use), but browse with the parent page and you will lose teh iframe as well. Hope that was the explanation you were looking for :)
至于你的第二个问题,iframe 的行为就像一个 ebmedded 页面:你可以在不影响父级的情况下浏览 iframe 中你想要的所有内容(当然像你想要使用的 javascript 调用除外),但浏览父页面和你也会失去 iframe。希望这是您正在寻找的解释:)