我想在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)
做这个的最好方式是什么?
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)