how to use "this" in this jquery function
I am trying to write a function where I need to reference "this" inside of window.setTimeou开发者_如何学JAVAt. Currently it doesn't work. How can I rewrite this so it works? Thanks.
$(function() {
$('li a').click(function() {
$(this).parent().css('background-position','left top');
window.setTimeout("$(this).css('font-size','40px');",1000);
});
});
As you saw, this
has a different meaning inside a setTimeout()
.
One solution is to store the correct value of this
in a variable, and reference it in the anonymous function that you pass in.
$(function() {
$('li a').click(function() {
$(this).parent().css('background-position','left top');
var th = this;
window.setTimeout(function() {
$(th).css('font-size','40px');
},1000);
});
});
Another option is to use jQuery's $.proxy()
which retains the value of this
for you.
$(function() {
$('li a').click(function() {
$(this).parent().css('background-position','left top');
window.setTimeout($.proxy(function() {
$(this).css('font-size','40px');
}, this)
,1000);
});
});
Otherwise, you could create a closure.
$(function() {
$('li a').click(function() {
(function( th ) {
$(th).parent().css('background-position','left top');
window.setTimeout(function() {
$(th).css('font-size','40px');
}
,1000);
})( this );
});
});
You need to create a closure inside your setTimeout call.
$(function() {
$('li a').click(function() {
var $this = $(this);
$this.parent().css('background-position','left top');
window.setTimeout(function () {
$this.css('font-size','40px');
},1000);
});
});
Should be much closer.
window.setTimeout(function(){$(this).css('font-size','40px')},1000);
No quotes. And it needs to be a function.
精彩评论