在Asp.net中用JQuery禁用动态生成Html按钮的问题
问题分析与解决方案
嘿,我一眼就看出问题出在哪了——Ajax回调里的this指向不对!
你看,当你点击按钮触发事件时,click回调里的this确实是按钮元素,但Ajax是异步操作,等到done回调执行的时候,上下文已经变了,这时候$(this)根本不是你点击的那个按钮,所以不管用prop还是attr都找不到目标,自然没法禁用它。
下面给你三种靠谱的解决办法,挑你喜欢的用就行:
方法1:提前缓存按钮对象(最推荐)
在click事件里先把按钮存成变量,回调里直接用这个变量,就不会有上下文问题了:
$("#send_request_button").on('click', function () { // 把当前按钮缓存起来 const $targetBtn = $(this); $.ajax({ url: "SendRequest", method: "GET", }).done(function (request_result) { if (request_result != null && request_result == '1') { alert("Attempting button disabling"); // 用缓存的对象禁用按钮 $targetBtn.prop("disabled", true); } else { alert("Could not disable Button"); } }); });
方法2:用箭头函数绑定上下文
箭头函数不会改变this的指向,会继承外层click回调的上下文,这样done里的this还是按钮元素:
$("#send_request_button").on('click', function () { $.ajax({ url: "SendRequest", method: "GET", }).done((request_result) => { // 这里换成箭头函数 if (request_result != null && request_result == '1') { alert("Attempting button disabling"); $(this).prop("disabled", true); } else { alert("Could not disable Button"); } }); });
方法3:直接通过ID重新获取按钮
因为你的按钮有唯一IDsend_request_button,直接在回调里重新获取元素也能解决问题,这种方法最简单直接:
$("#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"); // 直接通过ID获取按钮并禁用 $("#send_request_button").prop("disabled", true); } else { alert("Could not disable Button"); } }); });
另外还有两个小细节提醒你:
- 禁用按钮优先用
prop("disabled", true),而不是attr——因为disabled是布尔类型的属性,prop专门用来处理这类元素状态,比attr更可靠。 - 你的视图代码里多了一个多余的
},就是在Response.Write代码块的末尾,记得删掉它,不然会导致页面语法错误:
<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\"/>"); } } <!-- 这里之前多了一个},要移除 --> </div>
内容的提问来源于stack exchange,提问作者fs71gh
相关产品推荐
相关产品推荐

