18

我正在浏览http://docs.jquery.com/How_jQuery_Works并发现包含$.click()事件的要求$(document).ready()甚至有点奇怪。我的困难如下:

  • 当文档加载时,控件将进入$(document).ready()功能,但它会继续执行$.click()吗?(基于它不会的行为。但是当控件进入正常功能时,为什么它不进入$.click()功能?)
  • 由于用户只有在文档准备好后才能看到 url,所以真的需要嵌入其中$.click()$(document).ready()
4

5 回答 5

26

How jQuery Works 文档使用绑定.click()内部的示例来确定在函数执行时已经创建$(document).ready()了事件绑定到的元素。.click()

.click()函数作为参数调用的函数不会在与其前一个选择器匹配的节点上执行.click(),而是将函数绑定到匹配的节点' onclick

如果你试图做这样的事情:

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

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

此外,如果您在创建某些<a>标签时执行此操作,则只有已创建的标签才会获得绑定事件。<a>绑定函数后创建的标签将没有.click()绑定。

所以在 jQuery(和其他 JavaScript 框架)中,你会经常看到在一个$(document).ready(function(){});

于 2012-04-10T16:38:06.703 回答
6

这里关注的不是实际调用.click(),而是调用它的元素的选择器。

例如,如果有一个元素,id="myButton"那么您将引用它:

$('#myButton')

但是,如果该元素尚未加载(即,如果文档尚未准备好并且您不知道当前加载了哪些元素),则该选择器将找不到任何内容。所以它不会调用.click()任何东西(绑定事件或触发它,取决于参数.click())。

您可以使用其他方法,例如 jQuery.on()函数,它可以将事件绑定到公共父元素,并从文档生命后期添加的事件中过滤“冒泡”事件。但是如果你只是使用一个普通的选择器并调用一个函数,那么选择器需要在 DOM 中找到一些东西才能让函数做任何事情。

于 2012-04-10T16:40:45.230 回答
1

是的,您需要确保要向其中添加点击处理程序的 DOM 元素存在,您可以通过准备好的文档知道这一点。

于 2012-04-10T16:38:26.047 回答
1

$(document).ready(..)方法试图解决的问题是页面的 javascript 代码执行与页面中的控件被绑定的时间之间的紧张关系。ready一旦文档准备好并且 DOM 元素可用,该函数将触发,因此 javascript 代码可以对 DOM 做出合理的假设

最常见的例子是 javascript 代码相对于它试图操作的 DOM 元素的位置。考虑

<script>
$('#target').click(function() {
  alert('It was clicked');
});
</script>
<div id="target">Click Me</div>

In this particular example the javascript will not function as intended. When the script block is entered the click line is run and there currently is no DOM element with the id target hence the handler binds to nothing. There is nothing really wrong with the code, it just had the unfortunate timing to run before the DOM element was created.

In this example the problem is obvious because the code and DOM element are visually paired together. In more complex web pages though the javascript is often in a completely separate file and has no visual guarantees about load ordering (nor should it). Using the $(document).ready(..) abstraction removes the question of ordering as a potential source of problems and facilitates proper separation of concerns

于 2012-04-10T16:43:22.973 回答
0

Javascript 通常在读取标签后立即开始执行。这意味着在将脚本放在头部的标准实践中,还没有创建任何元素供您绑定点击处理程序。甚至身体元素还不存在。使用 jQuery.ready 会延迟执行代码,直到所有 DOM 元素都已加载。

于 2012-04-10T16:41:03.350 回答