jquery对this使用removeAttr无效

用jquery写了一个功能,就是点击按钮后按钮变为disabled,处理完成后再删除disabled。在函数内调用

$(this).attr("disabled", "disabled");

没什么问题,按钮变得不可用,但是处理完成后调用

$(this).removeAttr("disabled");

就不起作用了,但是用普通得DOM选择器就能起作用,类似这样

$("#form button").removeAttr("disabled");

一直没搞懂为啥不能用,我的jquery版本是v3.4.1

阅读 4.6k
3 个回答
let self= $(this);
 self.removeAttr("disabled");  失败
$(document).ready(function () {
   $("#form button").click(function () {
let self= $(this);
       let status = $("#status");
       let email = $("#account-input").val();
       let pwd = $("#pwd-input").val();
       status.text("处理中...");
       $(this).attr("disabled", "disabled"); // 成功
       $.ajax({url: "/verify", type: "POST", dataType: "text", error: function (e) {
            status.text(e.status + " 服务器错误");
           }, success: function (result) {
                if (result === "1"){
                    status.text("登陆成功,正在跳转...");
                    window.location.href = "/store";
                }else{
                    status.text("登陆失败,请检查账户");
                }
           }, complete: function () {
                // $("#form button").removeAttr("disabled"); 成功
               self.removeAttr("disabled");  失败
           }, timeoutSeconds: 3, data: {"type": "login", "email": email, "pwd": hex_md5(pwd), "remember": document.getElementById("remember").checked}, contentType: "application/x-www-form-urlencoded; charset=UTF-8"})
   }
   setTimeout(function (){status.text("")}, 2000);
   });
$(document).ready(function () {
   $("#form button").click(function () {
       let status = $("#status");
       let email = $("#account-input").val();
       let pwd = $("#pwd-input").val();
       status.text("处理中...");
       $(this).attr("disabled", "disabled"); // 成功
       $.ajax({url: "/verify", type: "POST", dataType: "text", error: function (e) {
            status.text(e.status + " 服务器错误");
           }, success: function (result) {
                if (result === "1"){
                    status.text("登陆成功,正在跳转...");
                    window.location.href = "/store";
                }else{
                    status.text("登陆失败,请检查账户");
                }
           }, complete: function () {
                // $("#form button").removeAttr("disabled"); 成功
                $(this).removeAttr("disabled");  失败
           }, timeoutSeconds: 3, data: {"type": "login", "email": email, "pwd": hex_md5(pwd), "remember": document.getElementById("remember").checked}, contentType: "application/x-www-form-urlencoded; charset=UTF-8"})
   }
   setTimeout(function (){status.text("")}, 2000);
   });

clipboard.png

你这两个 this 作用域都不一样 ←_←。

this 到底指向谁,这问题可以说是 JS 基本功了。

要么换 ES6 箭头函数;要么外层声明个变量 var that = this;,里层用 $(that) 而不是 $(this)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题