在optgroup中选择一个选项后转到URL

时间:2013-05-23 16:51:37

标签: javascript jquery optgroup

我想学习如何使用JavaScript(或jQuery库)来转到在optgroup标签内指示为option标签值的url。

使用包含选项标签的简单一级选择标记,解决方案可以类似于in this post所述的解决方案:

<FORM NAME="nav"><DIV>
<SELECT NAME="SelectURL" onChange=
"document.location.href=
document.nav.SelectURL.options[document.nav.SelectURL.selectedIndex].value">
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/jsnav.html"
SELECTED>Please select an item:
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/">
Main page on HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/choices.html">
Choices in HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/tables.html">
Tables and forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/methods.html">
Form submission methods (GET and POST)
</SELECT><DIV>
</FORM>

我尝试将它与带有选项标签的两级选择标签一起使用 - 这对我来说不起作用。我很感激能帮助您调整此代码。

2 个答案:

答案 0 :(得分:2)

当用户选择一个选项时,使用此选项:

$('select[name="SelectURL"]').change(function() {
    window.location.replace($(this).val());
});

或者当用户点击提交按钮时:

$('form[name="nag"]').on('submit' function(e){
    e.preventDefault();
    window.location.replace($('select[name="SelectURL"]').val());
});

您还应该像这样清理HTML:

<FORM NAME="nav">
    <DIV>
        <SELECT NAME="SelectURL">
            <OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/jsnav.html" SELECTED>Please select an item:</OPTION>
            <OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/"> Main page on HTML forms</OPTION>
            <OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/choices.html"> Choices in HTML forms</OPTION>
            <OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/tables.html"> Tables and forms</OPTION>
            <OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/methods.html"> Form submission methods (GET and POST)</OPTION>
        </SELECT>
    <DIV>
</FORM>

答案 1 :(得分:0)

首先摆脱内联onChange事件处理程序:

<FORM NAME="nav"><DIV>
<SELECT NAME="SelectURL">
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/jsnav.html"
SELECTED>Please select an item:
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/">
Main page on HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/choices.html">
Choices in HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/tables.html">
Tables and forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/methods.html">
Form submission methods (GET and POST)
</SELECT><DIV>
</FORM>

然后只需添加一个事件监听器:

$(document).ready(function() 
{ 
  $('select[name=SelectURL]').change(function(v)
  {
    window.location.replace( $(this).val() );
  });
});