jQuery自定义函数错误"this"参考

jQuery custom function wrong "this" reference

我需要在 jQuery 中多次执行相同的代码,所以我决定制作自己的 jQuery 函数。

目前看起来是这样的:

                jQuery.fn.extend({
                fooFunction: function () {
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: "includes/thescript.php",
                        success: function (data)
                        {
                            $(this).html(data);
                        }, complete: function () {
                            // do sth
                        }
                    });
                    return $(this);
                }
            });

但现在我遇到了问题,"this" 似乎引用了错误的实例,而在成功函数“$(this).html 中使用它时(数据);”。

当我改用 ID 时,例如$("#TheID").html(数据);它有效,但为什么不使用 "this"?

Between: 我用以下函数调用函数: $("#TheID").fooFunction()

在 jQuery ajax 回调中,“this”是对 ajax 请求中使用的选项的引用。它不是对 DOM 元素的引用。

有关详细信息,请访问此 link $(this) inside of AJAX success not working

函数缓存的开头$(this)然后用那个代替。

this 在函数引用中指向函数上下文而不是目标元素。

试试这个。

jQuery.fn.extend({
    fooFunction: function () {
        var $this = $(this);
        $.ajax({
            type: "POST",
            cache: false,
            url: "includes/thescript.php",
            success: function (data)
            {
                $this.html(data);
            }, complete: function () {
                // do sth
            }
        });
        return $this;
    }
});

问题是,当您在提供给 success 参数的匿名函数中时,this 的范围会发生变化。要解决此问题,您可以将来自外部作用域的 this 引用存储在一个变量中,如下所示:

jQuery.fn.extend({
    fooFunction: function () {
        var $el = $(this);
        $.ajax({
            type: "POST",
            cache: false,
            url: "includes/thescript.php",
            success: function (data) {
                $el.html(data);
            }, 
            complete: function () {
                // do something
            }
        });
        return $el;
    }
});