ASP .Net jQuery DropDownList 更改事件

ASP .Net jQuery DropDownList change event

我想用 ASP .Net 触发 jQuery 更改事件。 这是 ASP 和 jQuery 代码的一部分:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="body">
<p>
    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</p>
<script type ="text/javascript">
    $('#DropDownList1').change(function() {
        alert( "Handler for .change() called." );
    });
</script>
</asp:Content>

试图通过 ID #body_DropDownList1 和 #DropDownList1 获取元素。 不幸的是,两种情况都没有输出。

如果您在开发人员工具中检查下拉列表元素,您会注意到 ID 实际上不是 DropdownList1。 Asp 根据 ID 属性 生成一个 id 以防止重复,因此呈现不同。您不能依赖于复制它生成的那个,因为它可能会使用不同的 ClientID 呈现它。不过,您可以将 CssClass 设置为 select:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="body">
<p>
    <asp:DropDownList CssClass="DropdownList1" ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
 </p>
 <script type="text/javascript">
    $('.DropdownList1').change(function() {
        alert( "Handler for .change() called." );
    });
 </script>
 </asp:Content>

您还可以 select 基于 ClientID(实际呈现在客户端上的 ID)的元素,如下所示:

$("#<%=DropdownList1.ClientID %>")