如何在AJAX请求成功后移除按钮的data-orignal-text属性?
问题描述
在AJAX提交表单的场景中,请求成功后按钮自动被添加了data-orignal-text属性。相关代码如下:
初始按钮代码
<button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button>
AJAX处理代码
$(document).on("submit", "#formVerify", function (e) { e.preventDefault(); // 阻止表单默认提交行为 var form = $(this); BtnLoading(); $.ajax({ method: 'POST', url: form.action, data: form.serialize(), success: function (response) { if (response.status == 1) { if(response.user_role == 1) { window.location.href = globalSiteUrl + "/admin/dashboard"; }else if(response.user_role == 3){ window.location.href = globalSiteUrl + "/admin/user_match"; }else{ window.location.href = globalSiteUrl + "/admin/dashboard"; } } else { $('#idAlertErrorMsg').show() $('#idScriptErrorMsg').html(response.message) alert_message_fadeout(); } BtnReset(); } }); return false; });
请求后的按钮输出
<button type="submit" class="btn btn-primary btn-lg btn-block loader" id="idBtn" data-orignal-text="Verify">Verify</button>
需求:在AJAX成功回调中移除该data-orignal-text属性。
解决方案
直接在AJAX的success回调函数中,调用jQuery的removeAttr()方法即可移除目标属性。将移除操作放在BtnReset()之后(或根据业务逻辑调整位置):
修改后的AJAX成功回调代码:
success: function (response) { if (response.status == 1) { if(response.user_role == 1) { window.location.href = globalSiteUrl + "/admin/dashboard"; }else if(response.user_role == 3){ window.location.href = globalSiteUrl + "/admin/user_match"; }else{ window.location.href = globalSiteUrl + "/admin/dashboard"; } } else { $('#idAlertErrorMsg').show() $('#idScriptErrorMsg').html(response.message) alert_message_fadeout(); } BtnReset(); // 移除data-orignal-text属性 $('#idBtn').removeAttr('data-orignal-text'); }
注意事项
- 确保属性名拼写与实际一致:这里是
data-orignal-text(注意是orignal而非original),拼写错误会导致移除操作失效。 - 若按钮为动态生成元素,可结合表单上下文使用
form.find('#idBtn')选择器,避免出现选择错误。
内容的提问来源于stack exchange,提问作者test123
相关产品推荐
相关产品推荐

