为什么在jQuery中使用document.ready [英] Why document.ready is used in jQuery

查看:88
本文介绍了为什么在jQuery中使用document.ready的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery中 $(document).ready()的确切用法是什么?我们可以有两个 $(document).ready( )

What is the exact use of $(document).ready() in jQuery and can we have two $(document).ready() in a webpage?

推荐答案

页面无法安全操作,直到文档已经准备就绪。通常人们会在文档的开头写< head> 甚至在编写< body> 之前。因此,从技术上讲,如果您正在操作< body> 内容中的内容,则执行时不存在

A page can't be manipulated safely until the document is "ready." Generally people write <script> tags in the starting of the document, in the <head> even before the <body> is written. So, technically, if you are manipulating something from the <body> contents, it is not present at the time of execution.

因此,jQuery的 $(文档).ready()等待HTML Document内容完全加载并准备就绪,将所有元素渲染到窗口对象后,或简而言之,完成对正文的加载。

So, jQuery's $( document ).ready() waits for the HTML Document content to be loaded fully and become ready, after rendering all the elements into the window object or in a nutshell, completes the loading of the body.

然后HTML文档完全加载后,代码中的任何内容都会被执行,这样可以确保在执行JS代码时每个HTML元素都存在。

Then whatever content present in the code is executed, once the HTML document is fully loaded, which makes sure every HTML element is present as you execute your JS code.

签出:

关于绑定两个现成的处理程序,你为什么需要两个?您可以在单个函数中组合代码。您必须提供最小代码来解释。我假设你有类似的东西:

And about binding two ready handlers, why do you need two? You can combine the code in a single function. You must give a minimal code to explain. I assume you have something like this:

$( document ).ready( function () {
    // Code block 1 start...
    alert( "First Function..." );
    // Code block 1 end...
});

$( document ).ready( function () {
    // Code block 2 start...
    alert( "Second Function..." );
    // Code block 2 end...
});

是的,以上是可能的。此外,与上述没有区别:

And yes, the above is possible. Also, there's no difference from the above having:

$( document ).ready( function () {
    // Code block 1 start...
    alert( "First Function..." );
    // Code block 1 end...

    // Code block 2 start...
    alert( "Second Function..." );
    // Code block 2 end...
});

这篇关于为什么在jQuery中使用document.ready的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆