English 中文(简体)
jQuery 中删除元素的问题
原标题:Problems with removing elements in jQuery

我正试图与 jQuery 一起从页面中删除一个对象。 我也想要动画删除。 目标是使元素淡出( ), 等等, 然后删除( ) 。 但似乎拒绝等待删除元素, 即使我在一个设置Timeout () 函数中使用它 。 我如何才能使元素淡出( ), 然后移除它?

$("button").click(function() {
    $(this).fadeOut();
    setTimeout(function() { $(this).remove();}, 1000);
});
最佳回答

在您的超时功能中, this 不是你想的那样 - 它实际上是全球 window 对象。

您应该使用“完成回调” :

$("button").click(function() {
    $(this).fadeOut( slow , function() {
        $(this).remove();
    });
});

永远不要混合 setTimeout 和动画队列。 “em> interinterleave 两者,即有一个完成回调启动计时器,或者有一个计时器启动动画,都好,但假设您可以同时启动1000米动画和一个1000米计时器,并同时完成它们,是永远行不通的。

EDIT 固定代码 - 完成回覆时不需要 self , 我仍然在想 setTimeout this 当我写这个的时候!

问题回答

Read manual carefully: http://api.jquery.com/fadeOut/

淡出() 方法有一个回调, 在淡出完成后引用。 要使用它 :

$("button").click(function() {
    $(this).fadeOut(function() { $(this).remove();});
});

没有理由在淡出完成后等待一秒钟,然后才能删除元素,因为当元素被删除时,该元素是隐形的。

$( button ).click(function(){
    $(this).fadeOut(function(){$(this).remove()});
});​

"http://jsfiddle.net/AZDST/1/" rel="无尾随" >DEMO

何不干脆用淡出后退的回调呢?

$("button").click(function() {
    $(this).fadeOut(function(){$(this).remove();});
});

试试这个,也许有帮助:

$("button").click(function() {
    (function(that) {
        that.fadeOut();
        setTimeout(function() {
            that.remove();
        }, 1000);
    })($(this));
});




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签