javascript - 为什么我的每个类使用的 jQuery 片段不支持 setTimeout?

标签 javascript jquery

以下代码由于某种原因无法工作,它不喜欢 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();
    }); 
}

最佳答案

this 上下文在 setTimeout 场景中丢失。如果您尝试在 setTimeout 中使用 console.log(this),您将找到 window 对象。

Use .bind: JavaScript’s Bind Allows Us to Set the this Value on Methods

试试这个:

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);
    }); 
}

关于javascript - 为什么我的每个类使用的 jQuery 片段不支持 setTimeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312268/

相关文章:

javascript - 如何使用 JEST 测试 fetch API 类?

javascript - 非法遮蔽(用 var 遮蔽 let)

javascript - 将javascript json对象转换为字符串

jquery - 更改选择框字体大小影响选项项长度

jquery - 使用 CSS 和 jQuery 将所有大写字母转换为正确的大小写

javascript - ECMA6 指令的动态 Controller

javascript - 动画背景图像到另一个 - CSS/JQuery

javascript - 考勤应用程序未捕获语法错误 : Unexpected token {

javascript - 如何获取点击时输入的值

php - 使用 javascript/ajax 提交具有不同输入类型的 php 表单