Javascript iframe 重新加载按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11287050/
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
Iframe reload button
提问by user1373771
I have looked on many websites but none of them seem to work right or I don't understand them. I would like a simple button that refreshes a certain iframe. The button would be on the parent page and the iframe name is "Right".
我查看了许多网站,但似乎没有一个可以正常工作,或者我不理解它们。我想要一个简单的按钮来刷新某个 iframe。该按钮将位于父页面上,并且 iframe 名称为“Right”。
回答by Fabrício Matté
There are many ways to do this. Assuming this iframe
markup:
有很多方法可以做到这一点。假设这个iframe
标记:
<iframe name="Right" src="http://www.example.com"></iframe>
We can do it with a function call:
我们可以通过函数调用来实现:
HTML
HTML
<button onclick="refreshIframe();">Refresh Iframe</button>
JS
JS
function refreshIframe() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
}
Or with inline JS:
或者使用内联 JS:
<button onclick="var ifr=document.getElementsByName('Right')[0]; ifr.src=ifr.src;">Refresh Iframe</button>
Or using an event listener:
或使用事件侦听器:
HTML
HTML
<button id="iframeRefresher">Refresh Iframe</button>
JS
JS
window.onload = function() {
document.getElementById('iframeRefresher').addEventListener('click', function() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
});
}
Same as above, now with support for IE <= 8 and using a function in the global scope as handlerinstead of an anonymous one:
与上面相同,现在支持 IE <= 8 并使用全局范围内的函数作为处理程序而不是匿名函数:
HTML
HTML
<button id="iframeRefresher">Refresh Iframe</button>
JS
JS
window.onload = function() {
var refresherButton = document.getElementById('iframeRefresher');
if (refresherButton.addEventListener)
refresherButton.addEventListener('click', refreshIframe, false);
else
refresherButton.attachEvent('click', refreshIframe);
}
function refreshIframe() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
}
All of this without even touching jQuery or any other library.
所有这一切甚至都没有触及 jQuery 或任何其他库。
Which of these you should use? Whichever you consider more maintainable and readable. Just avoid global vars whenever possible. I'd personally avoid inline JS with the markup, and the listeners seem to be unnecessary, but that's just me. Choose whichever suits you better.
您应该使用其中的哪一个?无论您认为哪个更易于维护和可读。尽可能避免使用全局变量。我个人会避免使用标记内联 JS,并且监听器似乎是不必要的,但这只是我。选择更适合您的那个。
回答by Dips
Add new id
in your iframe and try below code.
id
在您的 iframe 中添加 new并尝试以下代码。
var iframe = document.getElementById('FrameId');
$("button").click(function() {
iframe.src = iframe.src;
}):