2014-09-07 2 views
0

div에있는 각 요소를 배열에 저장하는 javascript/jquery 함수가 있습니다. 문제는 익명 함수 외부에 결과를 저장하지 않는다는 것입니다. 전역 변수를 어떻게 설정합니까?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); 
     }); 
    }); 
} 
+0

의 중복 가능성 [자바 스크립트의 변수의 범위는 무엇입니까? (http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) –

답변

2

입니다. 어디서든 당신이 (원하는 전역 변수가없는이 방법을 사용할 수 있도록 함수가 return 문을 가질 수

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); 
     }); 
    }); 
} 

을 대안으로 : 니어는 여전히 그냥 함수 범위에서 그것을 정의 사용하려는 경우) 소개 :

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; 
    }); 
} 
+0

는 첫 번째 시도했지만 단지 나 또한 두번째 시도 2 어레이의 마지막 옵션을 기록하며() { \t VAR의 stored_options의 =의 store_options() 함수 fv_tags 정의되지 않은 출력한다 \t console.log (stored_options); }}); – taptipblard

+0

firstone- 나는 문제가 slice_last_index (this) 함수에 있다고 생각한다. 나는 당신의 인덱스를 오버라이드한다고 가정한다. 두 번째 문제에 대해 - ($ (document) .ready가 아닌) 외부 범위에 정의 된 store_options()를 확인하고 fv_tags 함수의 정의를 확인해야합니다. –

+0

답이 맞습니다. 내 문제는 다차원 배열을 설정하는 것입니다 – taptipblard

0

당신은 또한 윈도우의 속성을 설정할 수 있습니다

<script> 
     var someVar; 
     function foo(){ 

     } 
    </script> 

모든 기능 외부 변수를 사용하고 사장님로 사용할 수 있습니다 전자, 즉

 window.propName = "asd";