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

ONO*_*NOZ 5 javascript jquery

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

一个例子:

$("div").each(function(){
    var content = $(this).attr('data-content')
    setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay'));
});?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/qmhmQ/

做这个的最好方式是什么?

the*_*dox 15

$("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'));
});?
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 关于你改变了什么以及为什么会这个问题的解释是一个不错的答案.一大堆代码并没有真正帮助任何人学习任何东西. (5认同)