2014-05-24 93 views
1

在下面的代码中,我尝试创建几个必须调用存储在函数数组中的不同函数的处理函数('buttonHandlers')。该数组是外范围的一部分:在内部函数中从父范围访问数组元素

buttonJson = {}; 
for (i = 0; i < buttonNames.length; i++) { 
    customHandler = buttonHandlers[i]; 
    buttonJson[buttonNames[i]] = function() { 
     customHandler.apply(); 
     $('#msg-dialog-confirm').dialog("close"); 
     $('body').remove('#msg-dialog-confirm'); 
     ... 
    }; 
} 

上述处理程序函数调用的功能的阵列(“buttonHandlers”)的非常最后一个数组元素的结果的代码。我希望每个处理函数只调用由数组索引指定的相关函数。我怎样才能做到这一点?

+0

试着用'buttonJson [buttonNames [I] =功能(customHandler) {' – juvian

+0

它没有办法。可能这个提示太短了。无论如何,我需要将该函数传递给此参数。 – PAX

回答

2

customHandler是一个全球性的,你覆盖它在每次迭代,你应该创建一个新的范围,价值锁定

buttonJson = {}; 
for (i = 0; i < buttonNames.length; i++) { 
    (function(button) { 
     buttonJson[button] = function() { 
      button.apply(); 
      $('#msg-dialog-confirm').dialog("close"); 
      $('body').remove('#msg-dialog-confirm'); 
      ... 
     }; 
    })(buttonHandlers[i]); 
} 
+0

谢谢!这就像一个魅力!此外,我们还必须传递来自'buttonNames [i]'的值并将其用作键值:'buttonJson [text]'。 – PAX