2009-09-18 37 views
5

¿Cuál es la mejor manera de cambiar su URL a través de una selección de html?Cambiar URL a través de html seleccionar

<select> 
<option selected="selected">Change to URL X</option> 
<option>Change to URL Y</option> 
</select> 

¿Qué Javascript se debe utilizar?

+0

[http://www.cs.tut.fi/~jkorpela/forms/navmenu.html](http://www.cs.tut.fi /~jkorpela/forms/navmenu.html) tiene una buena guía (que incluye algunas buenas razones por las que no deberías hacer esto). – Quentin

Respuesta

-3

añadiendo, por ejemplo, algo así como que en la cabecera

<script language="JavaScript" type="text/javascript"> 
function jumpMenu(targ,selObj,restore){ 
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'"); 
} 
</script> 

y su cuadro de selección se ve entonces como esto

<select onchange="jumpMenu('parent',this)> 
<option selected="selected">Change to URL X</option> 
<option value="http://www.example.com">Change to URL Y</option> 
</select> 
+3

-1. No use 'eval()'. No es necesario aquí y es realmente una mala práctica. http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx ... http://www.jslint.com/lint.html y otros –

6
<script type="text/javascript"> 
function navigateTo(sel, target, newWindow) { 
    var url = sel.options[sel.selectedIndex].value; 
    if (newWindow) { 
     window.open(url, target, '--- attributes here, see below ---'); 
    } else { 
     window[target].location.href = url; 
    } 
} 
</script> 

<select onchange="navigateTo(this, 'window', false);"> 
<option selected="selected" value="http://www.example.com/#X">Change to URL X</option> 
<option value="http://www.example.com/#Y">Change to URL Y</option> 
</select> 

Algunos valores útiles de target podrían ser 'window' (la ventana actual) o 'top' (para salir de un conjunto de marcos o un iframe). Si desea abrir una nueva ventana en su lugar, se puede utilizar navigateTo(this, 'someWindow', true);

El valor de '--- --- atributos' se ajusta con diversas propiedades como se documenta here for Mozilla y here for IE. Por ejemplo:

'height=300,width=400,top=100,left=100,statusbar=0,toolbar=1' 
+0

¡Excelente! El código anterior funciona sin problemas. –

5

Si tiene jQuery que podría hacer ...

javascript:.

$ ('# select_url') cambio (function (evnt) {$ = location.href (esto) .val();});

html:

...

Cuestiones relacionadas