我有以下代码:-
<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,因为这是一个多语言项目,所以我必须依赖 id。
我的 jquery 有什么问题?
感谢您的帮助和时间
最佳答案
选项元素内部不能有跨度:
将您的 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>
关于javascript - 在 <select> 中的 <span> 中获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784004/