【问题标题】:How to use $(this) on AJAX success?如何在 AJAX 成功中使用 $(this)?
【发布时间】:2018-03-01 02:45:58
【问题描述】:

表格的每一行都有按钮。当用户单击它时,会触发一个 sweetalert 以显示确认窗口。如果用户单击是,则执行 AJAX 以发布行值。

发布过程正在运行,但我无法在 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

【问题讨论】:

  • function 之外定义var elem = $(this);,或在function() { ... }.bind(this) 末尾定义bind this。函数声明的方式与您确实拥有自己的 this.

标签: jquery ajax sweetalert


【解决方案1】:

问题原因

函数声明的方式与您确实拥有自己的this,因此使用$(this) 不再让您获得触发事件的元素。

解决方案 1

在内部function()(包含ajax 调用的那个)之外定义var elem = $(this);

解决方案 2

bindthisfunction() { ... }.bind(this) 的末尾。

解决方案 3 (ES6)

箭头函数没有自己的this,因此将function() 替换为()=&gt; 也可以完成这项工作,但只有在支持 ES6 的浏览器中运行它(或者如果您使用像通天塔)。

【讨论】:

    【解决方案2】:

    还可以获取事件对象:

    $("#tbl_list_pemenuhan tbody").on('click','.btn_memo', function(event) {
    

    然后使用它:

    var elem = $(event.target);
    

    【讨论】:

    • 我建议不要使用通用术语(可能是或成为保留术语)作为变量名。由于使用$(this) 的jQuery,因此对元素的引用也已经存在。
    • 对于 $(this) 是 tbody 实例还是 btn_memo 实例,读者总是有疑问。我认为这更清楚了。至于elem 变量名,我同意你的看法,它只是 OP 对变量名的选择 :)
    • 我说的是你的变量命名event
    猜你喜欢
    • 2016-09-21
    • 2011-06-26
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多