2013-07-22 66 views
1

我有下面的代碼: -得到一個<span>裏面的ID內<select>

<div class="DropDownContainer"> 
    <select class="DropDown"> 
     <option><span id="lblPeriod">Period</span></option> 
     <option><span id="lblLike">Like</span></option> 
     <option><span id="lblYear">Year</span> </option> 
    </select> 
</div>  

現在我試圖讓所選擇的值的ID,我有以下的jQuery: -

 $('.DropDown').on('change', function() { 

      var id = $(this).children(":selected").attr("span.id"); 
      alert(id); 
     }); 

但是id未定義。 $(this).val()將返回文本,例如「Period」,「Like」或「Year」,但是我需要id,因爲這是一個multilang項目,所以我必須依賴id。

我的jquery出了什麼問題?

感謝您的幫助和時間

+0

當你把ID在選項元素,而不是在一個跨度選項元素中會發生什麼? (擺脫額外的跨度)? –

+2

選項標籤不能有子元素這就是爲什麼就不能正常工作 – Pete

+0

爲了支持皮特的commment http://stackoverflow.com/questions/11237807/can-i-use-html-tags-in-the-options-for -select-elements –

回答

2

選項元素不能擁有它裏面跨度:

更改您的HTML:

<select class="DropDown"> 
    <option id="period">Period</option> 
    <option id="like">Like</option> 
    <option id="year">Year </option> 
</select> 


$('.DropDown').on('change', function() { 
    var id = $(this).children(":selected").attr("id"); 
    alert(id); 
}); 

如果多國語言在Asp.net您的問題,您可以也有選項元素的資源鍵,如:

<asp:DropDownList id="MyDdl" runat="server"> 
    <asp:ListItem Value="period" Text="period" meta:resourcekey ="period_Item_MyDdl" /> 
    <asp:ListItem Value="like" Text="like" meta:resourcekey ="like_Item_MyDdl" /> 
    <asp:ListItem Value="year" Text="year" meta:resourcekey ="year_Item_MyDdl" /> 
</asp:DropDownList> 
+0

它仍然返回undefined! – Johann

+0

更新我的代碼 –

+0

這是由頁面,生成,因爲我使用的是,因爲我需要多語言的工作 – Johann

0

使用以下代碼:

$('.DropDown').on('change', function() { 

     var id = $(this).children(":selected").text().find("span").prop("id"); 
     alert(id); 
}); 
+0

我試過你的代碼,但我仍然沒有定義 – Johann

+0

@Johann試着通過刪除選項。 –

+0

@Johann看到我更新的答案。 –

0

使用find()prop()

var id = $(this).children(":selected").find('span').prop("id"); 
2

它的工作原理採用

<div class="DropDownContainer"> 
    <select class="DropDown"> 
     <option id="lblPeriod">Period</option> 
     <option id="lblLike">Like</option> 
     <option id="lblYear">Year</option> 
    </select> 
</div> 

$('.DropDown').on('change', function() { 
    var id = $(this).children(":selected").attr("id"); 
    alert(id); 
}); 

將該選項設置元素的ID。此外,您必須設置一個value屬性,才能將其作爲可提交表單工作。

看到小提琴:http://jsfiddle.net/YdXpv/1/

+0

until_b理想情況下,我會這樣做,但是我的代碼已生成,因爲我使用的是,因爲我需要使用multilang站點 – Johann

相關問題