使用“”时未运行的代码;.remove()"作用

Code not running when using ".remove()" function

本文关键字:remove 作用 quot 代码 运行 使用      更新时间:2023-09-26

我正在编写这个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();是违法的吗?

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

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

setTimeout(function(){
  $('#suc').hide('slow', function(){
    $('#suc').remove();
  });
},2500);

当您使用hide时,使用delay也是安全的,因此:

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

就足够了。

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


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

代码运行成功,但当我把它放进去时,它没有运行!!

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

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

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

您使用的是元素setTimout回调,您已经在setTimout之后用语句删除了它。在setTimeout的下一条语句移除id为#suc的元素后,将执行对setTimeout的回调在隐藏回调中删除#suc,以便删除后脚本不会访问它

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