在 document.ready 函数之外的 jQuery 中创建全局变量?

javascriptweb developmentobject oriented programming更新于 2025/11/10 19:56:17

要创建全局变量,您需要将变量放在 <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 Code 编辑器中选择选项"使用 Live Server 打开"。

输出

将产生以下输出 −

单击按钮 checkGlobalvariable 时,将显示以下输出−


相关文章


有用资源