为什么我的jQuery代码段使用for each类不支持setTimeout

Why does my jQuery snippet using for each class not support setTimeout?

本文关键字:each 不支持 setTimeout for 段使用 我的 jQuery 代码 为什么      更新时间:2023-09-26

由于某些原因,下面的代码不起作用,它不喜欢setTimeout部分,相反,我唯一能做的工作版本是没有延迟。。。

jQuery(".divhere").hide();
if(jQuery('.divhere').length >= 1){
    jQuery(".divhere").each(function() {
        setTimeout(function(el) {
            jQuery(this).slideDown("slow");
            jQuery(this).show();
        }, 1000);
    }); 
}

唯一有效的是:

jQuery(".divhere").hide();
if(jQuery('.divhere').length >= 1){
    jQuery(".divhere").each(function() {
        jQuery(this).slideDown("slow");
        jQuery(this).show();
    }); 
}

setTimeout场景中缺少this上下文。如果您尝试在setTimeout中查找console.log(this),您会发现window对象。

使用.bind:JavaScript的绑定允许我们在方法上设置此值

试试这个:

jQuery(".divhere").hide();
if(jQuery('.divhere').length >= 1){
    jQuery(".divhere").each(function() {
        setTimeout(function(el) {
            jQuery(this).slideDown("slow");
            jQuery(this).show();
        }.bind(this), 1000);
    }); 
}