在文件載入完畢之外建立 jQuery 全域性變數
要建立全域性變數,你需要將變數放在 <script> </script> 標籤內。以下是程式碼:-
程式碼示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button
onclick="createGlobalVariable()">checkGlobalVariable</button>
<script>
var globalVariable;
$(document).ready(function() {
function initializeGlobalVariable() {
globalVariable = [{
"name":"John",
"age":23
}];
}
initializeGlobalVariable();
});
function createGlobalVariable() {
if (globalVariable.length) {
console.log('The Global variable name
is='+globalVariable[0].name+" The Global variable age is="+globalVariable[0].age);
}
}
</script>
</body>
</html>要執行以上程式,請將該檔案儲存為“anyName.html(index.html)”,並右鍵單擊該檔案。在 VS 程式碼編輯器中,選擇“用 Live Server 開啟”選項。
輸出
這將產生以下輸出:-

當單擊 checkGlobalvariable 按鈕時,以下輸出將顯示:-

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP