2012-07-02 13 views
8

He buscado en muchos sitios web pero ninguno de ellos parece funcionar bien o no los entiendo. Me gustaría un botón simple que refresque cierto iframe. El botón estaría en la página principal y el nombre del iframe es "Derecha".Botón de recarga Iframe

Respuesta

15

Hay muchas formas de hacerlo. Suponiendo que esta iframe marcado:

<iframe name="Right" src="http://www.example.com"></iframe> 

lo podemos hacer con un function call:

<button onclick="refreshIframe();">Refresh Iframe</button> 

JS

function refreshIframe() { 
    var ifr = document.getElementsByName('Right')[0]; 
    ifr.src = ifr.src; 
} 

O

HTML con inline JS:

<button onclick="var ifr=document.getElementsByName('Right')[0]; ifr.src=ifr.src;">Refresh Iframe</button> 

o utilizando un event listener:

HTML

<button id="iframeRefresher">Refresh Iframe</button> 

JS

window.onload = function() { 
    document.getElementById('iframeRefresher').addEventListener('click', function() { 
     var ifr = document.getElementsByName('Right')[0]; 
     ifr.src = ifr.src; 
    }); 
} 

Igual que el anterior, sin w with support for IE <= 8 and using a function in the global scope as handler en lugar de un anónimo uno:

HTML

<button id="iframeRefresher">Refresh Iframe</button> 

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

Todo esto sin ni siquiera tocar jQuery o cualquier otra biblioteca.

¿Cuál de estos debe usar? Lo que considere más fácil de mantener y legible. Solo evite vars globales siempre que sea posible. Yo personalmente evitaría JS en línea con el marcado, y los oyentes parecen ser innecesarios, pero así soy yo. Elija el que más le convenga.

+0

Woah! ¡Nunca pensé que hubiera tantas maneras de hacer esto! ¡Ojalá alguien pudiera poner esto en un sitio sobre iframes! ¡Gracias! – user1373771

+0

@ user1373771 no hay problema, puede marcar esto como la respuesta aceptada cuando tenga tiempo, si eso es todo. ': P' –

-3

Agregue el nuevo id en su iframe e intente debajo del código.

var iframe = document.getElementById('FrameId'); 
$("button").click(function() { 
    iframe.src = iframe.src; 
}): 
+1

OP dijo 'nombre', no' id'. No hay jQuery en las etiquetas ni en ninguna otra parte de la pregunta. Y tienes una sintaxis inválida al final. –