Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้างตัวแปร Global ใน jQuery นอก document.ready

ประกาศตัวแปรกลางแจ้งในแท็ก <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>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

คลิกปุ่มจะแสดงค่าตัวแปร Global ใน Console