0

我想学习如何使用 JavaScript(或 jQuery 库)来访问一个 url,该 url 表示为 optgroup 标记内的 option 标记的值。

使用包含选项标签的简单的一级选择标签,解决方案可以类似于本文中描述的解决方案:

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

我尝试将它与 optgroup 标签内带有选项标签的两级选择标签一起使用——它对我不起作用。我会感谢您在调整此代码方面的帮助。

4

2 回答 2

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>
于 2013-05-23T16:53:39.440 回答
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() );
  });
});
于 2013-05-23T16:56:05.420 回答