JQuery 在 Asp.net 中禁用动态创建的 Html 按钮

JQuery Disable Dynamically Created Html Button in Asp.net

需要根据状态创建我视图中的按钮。

Index.cshtml:

<html>
<head>
    <script src="~/scripts/jquery-3.3.1.js"></script>
    <script src="~/scripts/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $("#send_request_button").on('click', function () {
            $.ajax({
                url: "SendRequest",
                method: "GET",
            }).done(function (request_result) {
                if (request_result != null && request_result == '1') {
                    alert("Attempting button disabling");
                    @*attempt 1*@
                    @*$(this).prop("disabled", true);*@
                    @*attempt 2*@
                    $(this).attr("disabled", "disabled");
                }else {
                    alert("Could not disable Button");
                }
            });
        });    
    </script>
</head>

<body>
<div>
        @{
        if (ViewBag.ButtonFlag != null && ViewBag.ButtonFlag)
        {
            Response.Write("<text id=\"send_request_text\"></text>");
            Response.Write("<input id=\"send_request_button\" type=\"button\" value=\"Send Insert Request\"/>");
        }
      }
    }
</body>
</html>

这是正确给出按钮并单击它,收到成功 jquery ajax 后的预期结果,在本例中为 1。但是 none 两次禁用动态按钮的尝试产生了预期的结果。

试试这个而不是 $(this) 在 done() 中使用元素 id 到 select 这是因为如果在其他函数中使用 'this' 关键字的范围将不可用:

 $("#send_request_button").on('click', function () {
        $.ajax({
            url: "SendRequest",
            method: "GET",
        }).done(function (request_result) {
            if (request_result != null && request_result == '1') {
                alert("Attempting button disabling");
                @*attempt 1*@
                @*$(this).prop("disabled", true);*@
                @*attempt 2*@
                $("#send_request_button").attr("disabled", "disabled");
            }else {
                alert("Could not disable Button");
            }
        });
    });