变量范围在这种情况下如何工作?

时间:2011-03-13 20:53:33

标签: javascript scope

嘿伙计们,我早些时候问了一个类似的问题而且我为双重发布道歉,但这对我想要的东西更有疑问。我花了好几个小时搞清楚这一点,到目前为止还没有提出太多。

有三个函数,一个是总体函数,然后是两个函数,它们由toggle事件触发。我希望第二个函数能够获取值并将其传递给第二个函数。

   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(){}
    )}

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery Data(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>");
            }
        )}

答案 1 :(得分: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);
  })
}