为什么要将代码包装到“文档就绪"中 [英] Why wrap code into 'document ready'

查看:59
本文介绍了为什么要将代码包装到“文档就绪"中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jquery的新手.请参见 http://w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_p的示例.在这里,单击单击我"按钮更改文本.我的问题是,为什么以下代码需要包装在$(document).ready(function(){ )}下.否则,它将无法正常工作.

非常感谢您的所有帮助,并非常感谢.

$("button").click(function(){
    $("p").hide();
  });

解决方案

是的,如果您没有将此代码包装在$(document).ready()处理程序中,则由于不加载DOM,这些对象将不存在.

这是一个简单的测试,可确保在调用DOM元素上的方法之前已准备好DOM.

I'm new to Jquery. See an example at http://w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_p. Here, clicking 'Click Me' button the text change. My question is why the following code need to wrapped under $(document).ready(function(){ )}. Otherwise, it doesn't work.

Thanks so much for all your help and really appreciate.

$("button").click(function(){
    $("p").hide();
  });

解决方案

Yes, if you didn't wrap this code in the $(document).ready() handler, the objects wouldn't exist because the DOM isn't loaded.

This is a simple test to ensure that the DOM is ready, before invoking methods on its elements.

这篇关于为什么要将代码包装到“文档就绪"中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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