javascript - 为什么在 <script> 标签之后需要 $(document).ready?

标签 javascript jquery ajax

为什么是$(document).ready<script> 之后需要标签?

如果我们不使用 $(document).ready 会发生什么?

最佳答案

$(document).ready是javascript代码,所以必须写在<script>中元素和加载 jQuery 之后。

如果不写$(document).ready ,您的代码不会等待 DOM 完全加载并立即执行 javascript 代码。

如果您在 <head> 中使用脚本那是使用/操作来自 DOM 的一些元素,你需要 ready , 否则你会得到 null/undefined . 如果您在 <body> 末尾使用脚本,那么您就安全了,因为所有元素都已加载。

原样引用自jQuery Docs

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

例子?当然!

头脑中没有准备好

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    alert($('#myname').val());
  </script>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />
</body>

</html>

正文末尾

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    alert($('#myname').val());
  </script>
</body>

</html>

准备就绪

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      alert($('#myname').val());
    });
  </script>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />

</body>

</html>

对于 <script><body> 的末尾, 你可以省略 ready .

关于javascript - 为什么在 &lt;script&gt; 标签之后需要 $(document).ready?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558233/

相关文章:

JQuery - 从找到的类之后开始迭代 tds 的子集

jquery - 不均匀的 div 样式

javascript - 右键单击,显示调色板,然后更改颜色并将值写入单击时输入

javascript - 停止 setInterval

javascript - Angular 2 中的 http 调用结果

javascript - 如何使用phonegap检查电话目录中的文件是否存在

javascript - jQuery().change 如何与 ajax 配合使用?

带有 ajax 的 Javascript 回调函数

javascript - 如何在 Javascript/Angularjs 中检测用户来自哪里的 url?

JavaScript 作用域