2017-04-06 76 views
0

我無法訪問在單獨文件中聲明的全局聲明的JavaScript變量。 我的代碼:無法從另一個文件訪問javascript變量

<script src="scripts/one.js"></script> 
<script src="scripts/two.js"></script> 

One.js:

var config = { 
    form: 'form', 
    validate: { 
     '#first-name': { 
      'validation': 'required', 
      'error-msg': 'Required Field' 
     }, 
     // other validation rules 
    } 
}; 

Two.js:

$.validate({ 
    modules: 'jsconf', 
    onModulesLoaded: function() { 
     $.setupValidation(config); 
    } 
}); 

我receieve錯誤

Uncaught ReferenceError: config is not defined 

頁面的加載。當我按照適當的順序包含腳本時,爲什麼會發生這種情況?

+1

是你正確的文件路徑? – Cruiser

+1

你確定它實際上在加載嗎?網絡標籤? – epascarello

+0

在控制檯的網絡下查看 – lustoykov

回答

2
window.yourGlobalVariable 

使用window.variable name在文件之間獲取變量。

0

問題是因爲變量是在函數中定義的。無論是移動它的功能之外,或使用window.varName

var a = 1; 
 

 
// File 1 
 
$(function() { 
 
    var b = 2; 
 
    window.d = 4; 
 
    console.log(a); 
 
}); 
 

 
// File 2 
 
$(function() { 
 
    var c = 3; 
 
    console.log(a); 
 
    console.log(d); 
 
    console.log(b); // This will throw an error because b is not defined in this scope 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我建議,如果你想了解更多,你瞭解JS scopes