我正在用jQuery制作一个todo列表Web应用程序。我有一个删除按钮,可以删除表中的整行。我让它工作得很好,但一旦我为删除按钮添加了动画,它就不再工作了。我希望用户单击"移除"按钮,按钮中会出现动画,然后该行被移除。我做错了什么?提前感谢您的帮助。
$("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毫秒后的回调,因此在动画完成后将删除父级。