[英]Go to URL after selecting an option in optgroup
我想學習如何使用JavaScript(或jQuery庫)來轉到在optgroup標簽內指示為option標簽值的url。
用一個簡單的,一個水平選擇包含標記的選項標簽,所述溶液可以是類似於描述在這篇文章 :
<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>
我嘗試將它與帶有選項標簽的兩級選擇標簽一起使用,而且它不適用於我。 我很感激幫助您調整此代碼。
當用戶選擇一個選項時,使用此選項:
$('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>
首先擺脫內聯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() );
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.