0

可能重复:
Javascript 关闭问题

在下面的代码中,TrueThis.aChoices[i]['CallBack']当点击事件创建时是一个函数,当点击事件实际发生时为“false”。如何将函数引用获取到单击事件处理程序中?

我的对象:

ATK.MultiChoiceDialog = function() {

   var TrueThis = this;
   var aChoices;

   this.Show = function(sTitle,sPrompt,aChoices){
      this.aChoices = aChoices;

      var HTML = '[snip]';
      $('body').append(HTML);

      for(var i in this.aChoices)
      {      
         console.log(TrueThis.aChoices[i]['CallBack']); // shows "function"
         $('#ATKDialogButton'+i).click(function(e){
            console.log(TrueThis.aChoices[i]['CallBack']); // shows "false" ???
            if(TrueThis.aChoices[i]['CallBack'])
            {
               TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
            }
         });      
      }
   }
};

我也试过这个:

for(var i in this.aChoices)
{      
   var CB = TrueThis.aChoices[i]['CallBack'];
   console.log(CB); // function
   $('#ATKDialogButton'+i).click(function(e){
      console.log(CB); // false
      if(TrueThis.aChoices[i]['CallBack'])
      {
         TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
      }
   });      
}
4

2 回答 2

1

jQuery 通过将事件数据传递给绑定到事件的回调函数来处理这种情况。

ATK.MultiChoiceDialog = function() {

   var TrueThis = this;
   var aChoices;

   this.Show = function(sTitle,sPrompt,aChoices){
      this.aChoices = aChoices;

      var HTML = '[snip]';
      $('body').append(HTML);

      for(var i in this.aChoices){ // in js the '{' should be on same line
         console.log(TrueThis.aChoices[i]['CallBack']); // shows "function"
          $('#ATKDialogButton'+i).click({i:i},function(e){ // data passed in with {i:i}
            console.log(TrueThis.aChoices[e.data.i]['CallBack']); // shows "function" 
            if(TrueThis.aChoices[e.data.i]['CallBack']){ // in js the '{' should be on same line
               TrueThis.aChoices[e.data.i]['CallBack'].call(aChoices[e.data.i]['Context']);
            }
         });      
      }
   }
};​
于 2012-10-10T18:20:43.487 回答
0

感谢评论,我得到了这个工作。首先创建一个新函数来“修复” i 的值,该函数返回事件处理程序的函数。

this.FixI = function (i){
   return function(e){
      if(TrueThis.aChoices[i]['CallBack'])
      {
         TrueThis.aChoices[i]['CallBack'].call(TrueThis.aChoices[i]['Context']);
      }
   }
}

使用新函数在循环中生成偶数处理函数:

for(var i in this.aChoices)
{
   $('#ATKDialogButton'+i).click(TrueThis.FixI(i));      
}

更新:看起来 Kevin B 找到了一种 Jquery 方法来解决不需要额外的“preserver”功能的问题。

于 2012-10-10T18:24:22.057 回答