Scenario:
My_Object = {
my_div: "#mydiv",
my_method: function()
{
$(this.my_div).fadeOut("slow", function() { $(t开发者_StackOverflow社区his.my_div).fadeIn("slow"); });
}
}
'this.my_div' is not being recognized in the fadeIn call, as 'this' doesn't point to the original object anymore. How to I pass the original object to the callback function?
Store "this" in temporary variable:
My_Object = {
my_div: "#mydiv",
my_method: function()
{
var tmp = this;
$(this.my_div).fadeOut("slow", function() { $(tmp.my_div).fadeIn("slow"); });
}
}
That's because inside the fadeOut() callback, this
is now the element being faded out. I assume you want to fade it back in so just do this:
My_Object = {
my_div: "#mydiv",
my_method: function() {
$(this.my_div).fadeOut("slow", function() {
$(this).fadeIn("slow"); // refers to the same object being faded out
});
}
}
The Javascript this
concept is a little confusing.
精彩评论