ประกาศตัวแปรกลางแจ้งในแท็ก <script> ก่อน $(document).ready()
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.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"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
คลิกปุ่มจะแสดงค่าตัวแปร Global ใน Console