开发者

Access External Objects From jQuery CallBack Functions

开发者 https://www.devze.com 2022-12-12 12:58 出处:网络
Scenario: My_Object = { my_div: \"#mydiv\", my_method: function() { $(this.my_div).fadeOut(\"slow\", function() { $(t开发者_StackOverflow社区his.my_div).fadeIn(\"slow\"); });

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消