匿名函数的javascript变量范围

时间:2014-09-07 06:47:29

标签: javascript jquery

我有这个javascript / jquery函数,其中我将div中的每个元素存储到数组中。问题是它不会将结果保存在匿名函数之外。你如何设置一个全局变量?

这是我的Javascript / jquery

function store_options(){
    var stored_options = new Array;
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    });
}

2 个答案:

答案 0 :(得分:2)

通常不建议在JavaScript中使用全局变量。 如果你还想使用它,只需在函数范围内定义它:

var stored_options = new Array;

function store_options(){    
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    });
}

作为替代方案,您的函数可以有一个return语句,因此您可以在任何地方使用它(这样就不会引入全局变量):

function store_options(){  
    var stored_options = new Array;  
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    return stored_options;
    });
} 

答案 1 :(得分:0)

您可以在所有功能之外使用变量

    <script>
      var someVar;
      function foo(){

      }
    </script>

你也可以设置窗口的属性并随意使用,即

       window.propName = "asd";
相关问题