通过html选择更改URL

Dan*_*nos 5 html url html-select url-rewriting

通过html选择更改URL的最佳方法是什么?

<select>
<option selected="selected">Change to URL X</option>
<option>Change to URL Y</option>
</select>
Run Code Online (Sandbox Code Playgroud)

应该使用什么Javascript?

Gra*_*ner 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>
Run Code Online (Sandbox Code Playgroud)

一些有用的值target可能是'window'(当前窗口)或'top'(打破框架集或iframe).如果你想打开一个新窗口,你可以使用navigateTo(this, 'someWindow', true);

'--- attributes ---'的值是使用MozillaIE中为此记录的各种属性设置的.例如:

'height=300,width=400,top=100,left=100,statusbar=0,toolbar=1'
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你有jQuery你可以做...

JavaScript的:

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

HTML:

...


小智 -3

例如在标题中添加类似的内容

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

然后你的选择框看起来像这样

<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>
Run Code Online (Sandbox Code Playgroud)

  • -1。不要使用“eval()”。这里没有必要,而且这是非常糟糕的做法。http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx ... http://www.jslint.com/lint.html 等 (3认同)