Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在setTimeout()中使用$(this);_Javascript_Jquery - Fatal编程技术网

Javascript 在setTimeout()中使用$(this);

Javascript 在setTimeout()中使用$(this);,javascript,jquery,Javascript,Jquery,我想在jQuery中动态设置超时。动态设置的超时函数需要使用$(“this”),但我似乎无法让它工作 例如: $("div").each(function(){ var content = $(this).attr('data-content') setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay')); });​ 最好的方法是什么 $("div").each(function(){ va

我想在jQuery中动态设置超时。动态设置的超时函数需要使用$(“this”),但我似乎无法让它工作

例如:

$("div").each(function(){
    var content = $(this).attr('data-content')
    setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay'));
});​

最好的方法是什么

$("div").each(function(){
    var content = $(this).attr('data-content'),
        $this = $(this); // here $this keeps the reference of $(this)
    setTimeout(function() {

      // within this funciton you can't get the $(this) because
      // $(this) resides within in the scope of .each() function i.e $(this)
      // is an asset of .each() not setTimeout()
      // so to get $(this) here, we store it within a variable (here: $this) 
      // and then using it

        $this.html(content);
    }, $this.attr('data-delay'));
});​

将$(this)从settimeout中取出,并将其保存在局部变量中,在$(“div”)后面写上“self”。每个(function(){这一行

var self=$(this);

并进一步使用该自我。

您的代码应该如下所示:

  • 传递函数而不是字符串。 说明: 当将字符串传递给setTimeout时,会出现问题,因为它在与原始字符串不同的范围内运行,因此会出现错误

  • 使用jQuery
    data()
    方法

    $("div").each(function(){
         var content = $(this).attr('data-content'),
             $el = $(this),
             setContent = function(){
                $el.html(content);
             }
         setTimeout(setContent,$el.data('delay'));
    });​
    
  • 您可以将函数分配给变量,并将该变量作为参数传递给setTimeout,这是最干净的方法。

    使用closures()

    将字符串与
    setTimeout
    一起使用不是一个好主意。还要注意
    这个
    ,因为如果在闭包中使用,它可能会更改其上下文()

    如果使用数据属性,则可以使用jQuery数据函数

    $(“div”)。每个(函数(){
    var实例=$(此);
    var content=instance.data('content');
    var方法=函数(){
    html(content);
    };
    setTimeout(方法,instance.data('delay');
    });
    div{
    边框:1px纯黑;
    保证金:5px;
    高度:1.5em;
    }

    我只是扩展上面的答案之一

  • 使用类或id引用JavaScript中的div。这将避免页面中进一步的标记名冲突
  • 所以你更新的HTML是

    <div data-content="fus" data-delay="1000" class="dv"></div>
    <div data-content="ro" data-delay="2000" class="dv"></div>
    <div data-content="dah" data-delay="5000" class="dv"></div>​
    
    主线在哪里

    $this=$(this)

    我们将当前元素分配给setTimeout函数中使用的变量


    请参考此

    以下内容似乎是空白、可读性和透露意图的良好折衷

    $('div').each(function(){
        var element = $(this)
        var content = element.attr('data-content')
        var delayms = element.attr('data-delay')
        var action = function() { element.html(content) }
    
        setTimeout(action, delayms)
    })
    

    请参阅:

    一如既往:传递函数(闭包),而不是字符串。这样可以确保所有内容都在范围内,并且更易于读取、调试等。永远不要使用
    setTimeout(“…”
    ),而是使用
    setTimeout(function(){…})
    !如果您想使用
    数据-
    ,那么您不应该使用吗?@Quentin在$.attr中是否存在差异('data')和$.data(),除了长度?引用:从jQuery 1.4.3 HTML 5数据-属性开始,将自动拉入jQuery的数据对象。关于您更改了什么以及为什么要这样做的解释是一个不错的答案。一段代码并不能真正帮助任何人学习任何东西。@Quentin感谢您的建议,我尝试解释代码,请参阅并进行编辑如果有必要的话。字符串的求值不是传递给setTimeout break作用域吗?这样就不起作用了?你能解释一下闭包吗?我以前从未见过闭包。我添加了一些教程链接。我使用了css选择器,如div[data content^=]为了避免在每个div上添加一个类?很抱歉延迟,是的,您也可以使用选择器。请参阅此处的链接
    $('div').each(function(){
        var element = $(this)
        var content = element.attr('data-content')
        var delayms = element.attr('data-delay')
        var action = function() { element.html(content) }
    
        setTimeout(action, delayms)
    })