为什么$ .click()必须包含在$(document).ready()中? [英] Why should $.click() be enclosed within $(document).ready()?

查看:162
本文介绍了为什么$ .click()必须包含在$(document).ready()中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览 http://docs.jquery.com/How_jQuery_Works 并找到附上<$ c $的要求c> $。click() 中的事件$(文档).ready()甚至有点奇怪。我的困难如下:

I am going through http://docs.jquery.com/How_jQuery_Works and find the requirement of enclosing $.click() event in $(document).ready() even a little strange. My difficulties are as follows:


  • 当文档加载时,控件将输入 $(document).ready( )函数但它会继续执行 $。click()? (基于它不会的行为。但是当控件进入正常函数时,为什么不进入 $。click()函数?)

  • 由于用户只有在文档准备好后才能看到网址,是否真的需要在<$ c $中嵌入 $。click() c> $(document).ready()?

  • When the document loads, the control will enter $(document).ready() function but will it proceed to execute $.click()? (Based on the behavior it wouldn't. But when the control enters a normal function, why wouldn't it enter $.click() function?)
  • Since the user can see the url only after the document is ready, is it really required to embed $.click() within $(document).ready()?

推荐答案

jQuery Works文档如何使用绑定 .click() $(document).ready()里面要确定 .click()的元素函数执行时已创建event绑定。

The How jQuery Works document uses the example of binding a .click() inside of $(document).ready() to be certain that the element to which the .click() event is bound has been created when the function executes.

使用函数调用 .click()参数在与其前一个选择器匹配的节点上执行 <。c $ c> .click(),而是将该函数绑定到匹配节点的 onclick

The .click() called with a function as its parameter does not execute the .click() on the nodes matching its preceding selector, but rather binds the function to the matching nodes' onclick.

如果你想尝试做某事像这样:

If you were to attempt to do something like this:

$('a').click(function(){
  alert('clicked me');
});

...文件< head> 或在呈现任何< a> 元素之前,事件不会绑定到任何节点,因为没有节点匹配 $('函数执行时存在一个')选择器。

...in the document <head> or before any <a> element had been rendered, the event would not get bound to any node since no node matching the $('a') selector existed at the time the function executed.

此外,如果你在某些<已创建> 标记,只有已创建的标记才会获得绑定事件。绑定函数后创建的< a> 标签不会有 .click()绑定。

Furthermore, if you did it when some <a> tags had been created, only those already created would get the bound event. <a> tags created after the function was bound wouldn't have the .click() binding.

所以在jQuery(和其他JavaScript框架)中,你经常会看到在 $中添加事件处理程序,绑定小部件等的惯例(文件).ready(function(){});

So in jQuery (and other JavaScript frameworks), you'll often see the convention of adding event handlers, binding widgets, etc, inside a $(document).ready(function(){});

这篇关于为什么$ .click()必须包含在$(document).ready()中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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