2011-03-13 136 views
0

嘿,我早些时候问过类似的问题,并且对于双重发帖表示歉意,但是这对我想要的东西提出了更多问题。我花了几个小时弄清楚这一点,至今还没有提出。变量作用域在这种情况下会如何工作?

有三个功能,一个是全局功能,然后是两个功能,它们是由切换事件触发的。我想第二个函数做一些事情来获得一个值并将它传递给第二个函数。

function(){ 

    $('selector').toggle(

     //i want this to gather a value and store it in a variable 
     function(){ }, 

     //and i want this to accept the variable and value from the previous function 
     function(){} 
    )} 

回答

0

可以使用jQuery数据(http://api.jquery.com/jQuery.data/)来存储用于在选择各元素相匹配来存储和检索的值的值。

EXA:

function(a,b){ 



    $('selector').toggle(

      //i want this to gather a value and store it in a variable 
      function(){ 
      $(this).data("<YOUR_VARIABLE_NAME>", <YOUR_VARIABLE_VALUE>); 
      }, 

      //and i want this to accept the variable and value from the previous function 
      function(){ 
      var someVariable = $(this).data("<YOUR_VARIABLE_NAME>"); 
      } 
     )} 
+0

确定这就是怪异的一部分。我使用$(this).data()并使用alert()来检查值是否正确。它为第一个函数返回正确的值,但对于第二个函数,它返回null。一切都是一样的,但不知何故,它返回为空的第二个功能 – Ben

+0

已发布样本...请尝试在这些行,让我知道如果你仍然有问题... – Chandu

+0

好吧我用警报($(this))。 data(“variable_name”)),并且它返回第一个函数的正确值,但是它为第二个函数返回null。我完全按照你所说的......为什么不通过这项工作...... – Ben

0
function(){ 
    // this var will be in scope for anything inside this function 
    var availableInBoth; 

    $('selector').toggle(function(){ 
     // this var is only usable in this function 
     var availableHereOnly = 10; 
     availableInBoth = 10; 
    }, function(){ 
     console.log(availableInBoth); 
    }) 
} 
相关问题