0

我正在写这个 jquery 代码:

$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){$('#suc').hide('slow')},2500);
$('#suc').remove();

当我这样删除时$('#suc').remove();

$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){$('#suc').hide('slow')},2500);  

代码运行成功,但是当我输入它时,它没有运行!

那有什么问题?但是$('#suc').remove();在这里是违法的吗?

4

4 回答 4

1

setTimeout代码继续之前,调用不会等待回调运行,因此您将立即删除元素。当回调中的代码试图隐藏元素时,它不存在。

删除方法complete回调中的元素:hide

setTimeout(function(){
  $('#suc').hide('slow', function(){
    $('#suc').remove();
  });
},2500);
于 2013-02-05T09:08:04.570 回答
1

当您使用hide时,您也可以安全使用delay,所以:

$('#suc').show(700).delay(2500).hide('slow', function () {
  $(this).remove();
});

就足够了。

演示:http: //jsbin.com/isediz/2/


此外,作为澄清一点,关于:

代码运行成功,但是当我输入它时,它没有运行!

实际上代码运行(在某种意义上),问题是你remove不会等待两个异步事件(setTimeout.hide('slow'))。所以它会在这两个人完成他们应该做的事情之前得到执行。

于 2013-02-05T09:17:35.740 回答
0

您需要将 and 的remove()内部放在函数setTimeout的回调中hide()

$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);

setTimeout(function() { 
    $('#suc').hide('slow', function() { $(this).remove(); })
}, 2500);
于 2013-02-05T09:07:57.927 回答
0

您正在使用setTimout已在 setTimout 之后的语句中删除的元素回调。的回调将在setTimeout 的下一条setTimeout语句删除具有 id 的元素的语句之后执行。在隐藏回调中删除,以便在删除后不被脚本访问#suc#suc

$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){
      $('#suc').hide('slow', 
           function(){$(this).remove();
      }); 
},2500);
于 2013-02-05T09:06:22.030 回答