使用JQuery禁用时,下拉列表所选值在PostBack上重置

Drop Down List Selected Value Gets Reset On PostBack When Getting Disabled With JQuery

本文关键字:PostBack JQuery 下拉列表 使用      更新时间:2023-09-26

我有这样的问题,如果我在下拉列表的.change事件上使用JQuery禁用控件,则控件将重置为默认状态。

我有以下代码:

ASP.NET:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script type='text/javascript' src="jquery-1.11.0.min.js"></script>
<body>
<form id="form1" runat="server">
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
    <asp:ListItem Value="1">Item1</asp:ListItem>
    <asp:ListItem Value="2">Item2</asp:ListItem>
    </asp:DropDownList>
</div>
</form>
</body>
<script type="text/javascript">
$("#DropDownList1").change(function () {
    $("#DropDownList1").attr("disabled", "disabled");
});
</script>
</html>

代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

因此,使用该代码,如果将所选项目从DropDownList1切换到PostBack,它将重置为默认状态。如果Jquery没有禁用该控件,则不会重置该控件。

如何使其在禁用时在PostBack上保持其价值?

您可以删除Autopostback="True",这样就不会发生回发。。

<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Value="1">Item1</asp:ListItem>
    <asp:ListItem Value="2">Item2</asp:ListItem>
    </asp:DropDownList>

每当您在更改下拉项时必须对代码执行某些操作时,就会设置Autopostback="True"。。

尝试这样禁用。。

$("#DropDownList1").attr("disabled", true);