添加 jQuery 动画使我的删除按钮无法工作

Adding jQuery animation prevents my remove button from working

我正在使用 jQuery 制作待办事项列表 Web 应用程序。我有一个删除按钮,可以删除 table 中的整行。我让它工作得很好,但是一旦我为删除按钮添加了动画,它就不再起作用了。我想要发生的是用户单击删除按钮,按钮中出现动画,然后该行被删除。我究竟做错了什么?在此先感谢您的帮助。

$("table").on("click", ".btn-danger", function() {
  var fire = $("<span>").addClass("glyphicon glyphicon-fire").attr("aria-hidden", "true").fadeIn(1000);
  $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-danger btn-width").append(fire));
  $(this).parent().parent().remove(); // Remove entire row
});

首先,您在将 fadeIn 添加到 DOM 之前对其进行了设置,因此它无法正常工作。

另一方面,jquery 动画 运行 是异步的,因此您 运行 fadeIn,但就在它之后,您删除了父级。

我会这样做:

$("table").on("click", ".btn-danger", function() {
    var fire = $("<span>").addClass("glyphicon glyphicon-fire").attr("aria-hidden", "true")
    $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-danger btn-width").append(fire));
    var instance = this;
    fire.fadeIn(1000, function(){
        $(instance).parent().parent().remove(); // Remove entire row
    });
});

如果你看我的代码,我运行追加后的fadeIn,我使用了fadeIn的第二个参数,它是1000毫秒后的回调,所以parent 将在动画结束后被移除。