Javascript 为什么 $.click() 应该包含在 $(document).ready() 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10092762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why should $.click() be enclosed within $(document).ready()?
提问by Ken Russell
I am going through http://docs.jquery.com/How_jQuery_Worksand find the requirement of enclosing $.click()
event in $(document).ready()
even a little strange. My difficulties are as follows:
我正在浏览http://docs.jquery.com/How_jQuery_Works并发现封闭$.click()
事件的要求$(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()
?
- 当文档加载时,控件将进入
$(document).ready()
功能但它会继续执行$.click()
吗?(基于它不会的行为。但是当控件进入正常功能时,为什么它不会进入$.click()
功能?) - 由于用户可以看到URL后,才准备好文档,是不是真的需要嵌入
$.click()
内$(document).ready()
?
回答by Michael Berkowski
The How jQuery Works documentuses 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.
该如何jQuery的Works文档使用的结合的例子.click()
的内部$(document).ready()
可以肯定,对其中的元件.click()
事件绑定已经创建的功能执行时。
The .click()
called with a function as its parameter does not executethe .click()
on the nodes matching its preceding selector, but rather binds the function to the matching nodes' onclick
.
在.click()
与函数调用作为它的参数不执行的.click()
其前面的选择相匹配的节点上,而是结合的功能匹配的节点onclick
。
If you were to attempt to do something like this:
如果你试图做这样的事情:
$('a').click(function(){
alert('clicked me');
});
...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.
...在文档中<head>
或在<a>
呈现任何元素之前,事件不会绑定到任何节点,因为$('a')
在函数执行时不存在与选择器匹配的节点。
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.
此外,如果您<a>
在创建某些标签时执行此操作,则只有那些已创建的标签才会获得绑定事件。<a>
在函数绑定后创建的标签不会有.click()
绑定。
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(){});
因此,在 jQuery(和其他 JavaScript 框架)中,您经常会看到在一个内部添加事件处理程序、绑定小部件等的约定。 $(document).ready(function(){});
回答by David
It's not the actual call to .click()
which is the concern here, but rather the selector for the element on which it's called.
.click()
此处关注的不是实际调用,而是调用它的元素的选择器。
For example, if there is an element with id="myButton"
then you would reference it with:
例如,如果有一个元素 withid="myButton"
那么你可以用以下方式引用它:
$('#myButton')
However, if that element isn't yet loaded (that is, if the document isn't yet ready and you don't knowwhat elements arecurrently loaded), then that selector won't find anything. So it won't call .click()
on anything (either to bind the event or to fire it, depending on the argument(s) to .click()
).
但是,如果该元素还没有加载(即,如果该文件还没有准备好,你不知道哪些元素是当前加载),那么选择不会找到任何东西。所以它不会调用.click()
任何东西(绑定事件或触发它,取决于参数.click()
)。
You can use other approaches, such as the jQuery .on()
function, which can bind events to common parent elements and filter "bubbled up" events from ones added later later in the life of the document. But if you're just using a normal selector and calling a function then the selector needs to find something within the DOM in order for the function to do anything.
您可以使用其他方法,例如 jQuery.on()
函数,它可以将事件绑定到公共父元素,并从文档生命周期后期添加的事件中过滤“冒泡”事件。但是如果你只是使用一个普通的选择器并调用一个函数,那么选择器需要在 DOM 中找到一些东西,以便函数做任何事情。
回答by Maess
Yes, you need to make sure that the DOM element to which you are adding the click handler exists, any you know this by the document being ready.
是的,您需要确保要向其添加点击处理程序的 DOM 元素存在,您可以通过文档准备好知道这一点。
回答by JaredPar
The problem the $(document).ready(..)
method is trying to solve is the tension between the execution of the javascript code for the page and the time at which controls in the page are bound. The ready
function will fire once the document is ready and DOM elements are available hence the javascript code can make reasonable assumptions about the DOM
该$(document).ready(..)
方法试图解决的问题是页面 javascript 代码的执行与页面中控件的绑定时间之间的紧张关系。ready
一旦文档准备好并且 DOM 元素可用,该函数就会触发,因此 javascript 代码可以对 DOM 做出合理的假设
The most common example is the location of javascript code with respect to the DOM elements it's trying to operate on. Consider
最常见的例子是 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.
在此特定示例中,javascript 将无法按预期运行。当输入脚本块时,click
运行该行并且当前没有带有 id 的 DOM 元素,target
因此处理程序绑定到任何内容。代码没有什么问题,只是不幸在创建 DOM 元素之前运行了。
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
在这个例子中,问题很明显,因为代码和 DOM 元素在视觉上是配对的。在更复杂的网页中,尽管 javascript 通常位于一个完全独立的文件中,并且没有关于加载顺序的视觉保证(也不应该)。使用$(document).ready(..)
抽象消除了作为潜在问题来源的排序问题,并促进了关注点的适当分离
回答by Ryan P
Javascript usually starts executing as soon as the tag is read. This means that in the standard practice of putting scripts in the head, there are NO elements created yet for you to bind a click handler to. Even the body element doesn't exist yet. Using jQuery.ready delays executing your code until all DOM elements have been loaded.
Javascript 通常在读取标记后立即开始执行。这意味着在将脚本放入头部的标准实践中,还没有创建元素供您绑定点击处理程序。甚至 body 元素还不存在。使用 jQuery.ready 会延迟执行您的代码,直到所有 DOM 元素都已加载。