Để biến toàn cục truy cập được bên ngoài $(document).ready(), khai báo biến ở phạm vi toàn cục (bên trong thẻ <script> nhưng ngoài hàm ready).
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Biến toàn cục jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button onclick="checkGlobalVariable()">Kiểm tra biến toàn cục</button>
<script>
// Khai báo biến toàn cục
var globalVariable;
$(document).ready(function() {
function initializeGlobalVariable() {
globalVariable = [{
"name": "John",
"age": 23
}];
}
initializeGlobalVariable();
});
function checkGlobalVariable() {
if (globalVariable.length) {
console.log('Tên: ' + globalVariable[0].name + ', Tuổi: ' + globalVariable[0].age);
}
}
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, nhấn nút để xem console.
Kết quả console
Tên: John, Tuổi: 23
Lưu ý: Tránh lạm dụng biến toàn cục. Nên dùng module pattern hoặc ES6 modules để quản lý scope tốt hơn.