从jQuery回调函数访问外部对象
问题描述:
场景:
My_Object = {
my_div: "#mydiv",
my_method: function()
{
$(this.my_div).fadeOut("slow", function() { $(this.my_div).fadeIn("slow"); });
}
}
在"fadeIn"调用中无法识别"this.my_div",因为"this"不再指向原始对象.如何将原始对象传递给回调函数?
'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?
答
将"this"存储在临时变量中:
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"); });
}
}