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

2023-12-30

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

一个例子:

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

http://jsfiddle.net/qmhmQ/ http://jsfiddle.net/qmhmQ/

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


$("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'));
});​

DEMO http://jsfiddle.net/thecodeparadox/qmhmQ/6/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 setTimeout() 中使用 $(this) ; 的相关文章

随机推荐