jQuery animate 完整参数,仅用作匿名函数而不用作函数指针

jQuery animate complete parameter, only works as anonymous function not as function pointer

本文关键字:函数 animate 指针 参数 jQuery      更新时间:2023-09-26

我用以下jQuery动画删除了一个dom元素:

        var $id = $(this._id); // id of a dom element
        $id.animate({
            width:          "10vw",
            fontSize:       "0.33vw",
        }, 300, "swing", function() {
            $id.remove();
        });

这工作正常。但我想让它更短并尝试:

        var $id = $(this._id); // id of a dom element
        $id.animate({
            width:          "10vw",
            fontSize:       "0.33vw",
        }, 300, "swing", $id.remove);

这不。为什么不呢?我想,那是一样的...

$id.remove作为函数指针(我称之为函数引用)将失去其上下文,即this值,这意味着remove()不知道要处理哪个集合。

尝试传递$.proxy($.fn.remove, $id) .这将调用 jQuery 的 remove() 方法,使用 $id 的上下文。 $.proxy()Function.prototype.bind()的跨浏览器实现。

通常,看到

调用也包装在匿名函数中,以防止您遇到的问题。