本文介绍了在setTimeout()中使用$(this);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在jQuery中动态设置超时。动态设置的超时函数需要使用$(this),但我似乎无法使它工作。
I want to set timeouts dynamically in jQuery. The dynamically set timeout functions need to use $("this"), but I can't seem to get it working.
一个例子:
$("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'));
});
DEMO
这篇关于在setTimeout()中使用$(this);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!