如何在 AJAX 成功时使用 $(this)?
How to use $(this) on AJAX success?
table的每一行都有按钮。当用户单击它时,会触发 sweetalert 以显示确认 window。如果用户单击“是”,则会对 post 行值执行 AJAX。
post 进程正在运行,但我无法在 AJAX 成功调用后更改按钮属性和标签文本。这是我的脚本。
$("#tbl_list_pemenuhan tbody").on('click','.btn_memo', function() {
var no_penuh = $(this).closest('tr').find("td:eq(1)").text();
var no_minta = $(this).closest('tr').find("td:eq(2)").text();
var data = 'no_pnh='+no_penuh+'&no_mnt='+no_minta;
swal({
title : "Apa anda yakin?",
type : "warning",
showCancelButton : true,
confirmButtonColor : "#0C0",
confirmButtonText : "Ya!",
cancelButtonText : "Batal",
closeOnConfirm : true
},function(){
var elem = $(this);
$.ajax({
type : "POST",
url : "<?php echo site_url('con_atk/buat_memo_direct'); ?>",
data : data,
success : function(data){
elem.attr('disabled','disabled');
elem.closest('tr').find('label').text('SENT');
alert("SUCCESS");
}
});
});
});
注意:
在 AJAX 成功时,将执行警报但不会 elem
问题原因
函数声明的方式确实有它们自己的 this
,因此使用 $(this)
不再让您获得触发事件的元素。
解决方案 1
在内部 function()
(包含 ajax 调用的那个)之外定义 var elem = $(this);
。
解决方案 2
bind
this
结尾function() { ... }.bind(this)
。
解决方案 3 (ES6)
箭头函数没有它们自己的 this
所以用 ()=>
替换 function()
也可以完成这项工作,但只有在 ES6 中 运行 它才会起作用有能力的浏览器(或者如果你使用像 Babel 这样的转译器)。
您还可以获取事件对象:
$("#tbl_list_pemenuhan tbody").on('click','.btn_memo', function(event) {
然后使用:
var elem = $(event.target);
table的每一行都有按钮。当用户单击它时,会触发 sweetalert 以显示确认 window。如果用户单击“是”,则会对 post 行值执行 AJAX。
post 进程正在运行,但我无法在 AJAX 成功调用后更改按钮属性和标签文本。这是我的脚本。
$("#tbl_list_pemenuhan tbody").on('click','.btn_memo', function() {
var no_penuh = $(this).closest('tr').find("td:eq(1)").text();
var no_minta = $(this).closest('tr').find("td:eq(2)").text();
var data = 'no_pnh='+no_penuh+'&no_mnt='+no_minta;
swal({
title : "Apa anda yakin?",
type : "warning",
showCancelButton : true,
confirmButtonColor : "#0C0",
confirmButtonText : "Ya!",
cancelButtonText : "Batal",
closeOnConfirm : true
},function(){
var elem = $(this);
$.ajax({
type : "POST",
url : "<?php echo site_url('con_atk/buat_memo_direct'); ?>",
data : data,
success : function(data){
elem.attr('disabled','disabled');
elem.closest('tr').find('label').text('SENT');
alert("SUCCESS");
}
});
});
});
注意:
在 AJAX 成功时,将执行警报但不会 elem
问题原因
函数声明的方式确实有它们自己的 this
,因此使用 $(this)
不再让您获得触发事件的元素。
解决方案 1
在内部 function()
(包含 ajax 调用的那个)之外定义 var elem = $(this);
。
解决方案 2
bind
this
结尾function() { ... }.bind(this)
。
解决方案 3 (ES6)
箭头函数没有它们自己的 this
所以用 ()=>
替换 function()
也可以完成这项工作,但只有在 ES6 中 运行 它才会起作用有能力的浏览器(或者如果你使用像 Babel 这样的转译器)。
您还可以获取事件对象:
$("#tbl_list_pemenuhan tbody").on('click','.btn_memo', function(event) {
然后使用:
var elem = $(event.target);