[英]Referencing a drop down menu in jQuery from ASP.NET
這是一個新手問題。 我一直在使用jQuery一天左右。
我只想在下拉菜單中捕獲每個更改。
這是我的下拉菜單和參考:
<script src="Scripts/insertRootCauseElements.js" type="text/javascript"></script>
<asp:DropDownList ID="DropDownListRootCause" runat="server" > </asp:DropDownList>
這是我的處理程序:
$(document).ready(function () {
// var selectedValue = $('#DropDownListRootCause').selectedValue;
//var selectedIndex = $('#DropDownListRootCause').selectedIndex;
alert("HERE");
$('#DropDownListRootCause').change(function () {
alert("Changed " + $('#DropDownListRootCause').selectedIndex);
})
.change();
// if ($('#DropDownListRootCause').change) {
// alert("dd change " + selectedIndex);
// }
})
我嘗試了很多變化,但沒有什么對我有用。 在調試時,似乎我的jQuery不知道“DropDownListRootCause”是什么。
我在我的dd控件中設置了AutoPostBack = true,它找到了我的jQuery但是
$('#DropDownListRootCause').change(function () {
alert("Changed " + $('#DropDownListRootCause').selectedIndex);
})
仍然是虛假的。
我在調試時將DropDownListRootCause添加到'Watch',顯示'DropDownListRootCause'未定義'。 我試過雙引號和單引號但沒有運氣。
它必須是簡單的東西,但我看不到它。 有人可以幫忙嗎?
如果您在源HTML中注意到,ASP.Net會更改ID。 很多時候,它最終會看起來像: $ctr001_DropDownListRootCause
。 這就是您的選擇器無法正常工作的原因。
有兩種方法可以正確選擇您的select
菜單:
$('[id$="DropDownListRootCause"]')
這樣做的屬性以選擇器結束 。 $('#<%=DropDownListRootCause.ClientID %>')
ASP.Net會將完整的id寫入您的選擇器。 注意 :只有在您的.aspx
文件中包含javascript時才能使用此選項。 如果您嘗試在.js
文件中使用它,它將無法工作,因為ASP.Net在呈現頁面時不會對這些文件執行任何操作。 此外,選擇器的結尾可以修改為更具體:
$('select[id$="DropDownListRootCause"]')
編輯:
選擇器的結尾有陷阱。 如果此select
元素位於GridView
行或Repeater
,則選擇器將全部匹配。 假設你有這個GridView
:
<asp:GridView ID="gv"
runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownListRootCause" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
(我已經從中移除了絨毛)它會生成看起來像這樣的HTML:
<tr onclick="__doPostBack('gv','Select$0')">
<td>
<select name="gv$ctl03$DropDownListRootCause" id="gv_DropDownListRootCause_0"></select>
</td>
</tr>
<tr onclick="__doPostBack('gv','Select$1')">
<td>
<select name="gv$ctl04$DropDownListRootCause" id="gv_DropDownListRootCause_1"></select>
</td>
</tr>
<tr onclick="__doPostBack('gv','Select$2')">
<td>
<select name="gv$ctl05$DropDownListRootCause" id="gv_DropDownListRootCause_2"></select>
</td>
</tr>
<tr onclick="__doPostBack('gv','Select$3')">
<td>
<select name="gv$ctl06$DropDownListRootCause" id="gv_DropDownListRootCause_3"></select>
</td>
</tr>
<tr onclick="__doPostBack('gv','Select$4')">
<td>
<select name="gv$ctl07$DropDownListRootCause" id="gv_DropDownListRootCause_4"></select>
</td>
</tr>
同樣,我已經刪除了很多不需要的標記來顯示我正在談論的內容。 使用渲染的HTML,使用$('[id$="DropDownListRootCause"]')
將選擇5個 select
元素。 如果您嘗試將相同的事件代碼連接到所有5個元素,那么您沒問題。 但是,如果你只想用其中一個做某事,你需要讓選擇器更具體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.