我只想运行一个回调函数一次,如果它删除了某个类的所有元素,它应该运行,但由于某种原因,回调函数运行的次数是删除的元素数量的倍,所以这不是我想要的对于。
代码(形成插件)
$.plugin= {
clear: function(str){
$('.msg').fadeOut(200, function(){
$(this).remove();
if(typeof str.remove == 'function'){
str.remove.call(this);
}
});
}
}
最佳答案
最简单的方法是取消设置该功能:
$('.msg').fadeOut(200, function(){
$(this).remove();
if(typeof str.remove == 'function'){
str.remove.call(this);
str.remove = false;
}
});
<小时/>
贾奥尔德可能是对的。 以下代码使用所有 .msg 元素调用回调:
var $msgs = $('.msg').fadeOut(200, function(){
$(this).remove();
if(typeof str.remove == 'function'){
str.remove.call($msgs);
str.remove = false;
}
});
请注意,$('.msg')
速度很慢(尤其是在 IE 7 及更低版本中),并且不应在没有标记的情况下使用。
原因是他们不支持document.querySelectorAll (正如迈克·G所说)
关于javascript - jQuery:如何让回调函数只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9804442/