使用“”时未运行的代码;.remove()"作用
Code not running when using ".remove()" function
我正在编写这个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);
相关文章:
- jQuery.remove(Selector)没有'不起作用
- jQuery.remove()不起作用,而其他内置函数则起作用
- 如果我移除animateTo参数,.remove()回调函数将不起作用
- jQuery.remove()不起作用
- JQuery remove() 在 IE 中不起作用
- jquery find() 和 remove() 脚本标签不起作用
- jQuery remove 在映射集上运行时不起作用
- 将 jquery remove 方法设置为动画完成时的回调不起作用
- JavaScript remove 标签在 Mozilla 中不起作用
- remove() 方法在 animate() 中不起作用
- html()、append()对通过ajax调用来的元素不起作用,remove起作用
- 在AJAX函数中.remove()不起作用
- Remove()在mongodb中不起作用
- Jquery remove特性在IE中不起作用
- 为什么.remove()在回调函数中不起作用
- Knockout js remove不起作用
- Remove()对新元素不起作用
- Jquery remove()不起作用
- parentNode.remove()在IE中不起作用
- IE7: .remove()不起作用- element (byID)不存在