jQuery-是否需要$(document).ready? [英] jquery - Is $(document).ready necessary?

查看:137
本文介绍了jQuery-是否需要$(document).ready?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读在线教程,该教程指出如果<script></script>恰好位于</body>的顶部,则$(document).ready不必要b/c此时已加载文档.

I am reading an online tutorial that says if the <script></script> is right on top of </body> the $(document).ready is not necessary b/c the document has been loaded at that moment.

Q1>是吗?

第二季度

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script src="jquery.viewport.min.js"></script>

<script>
$(window).scroll(function() { // this line will track all mouse scroll event

});
</script>

$(窗口)是什么意思?这是一个jQuery选择器吗?如果是这样,则先前的声明看起来是正确的,因为我们不必将其包含在内

What does the $(window) mean? Is this a jquery selector? If it is, then the previous claim looks correct because we don't have to include this inside

$(document).ready(function() {

});

Q3>为什么我们在这里使用$ link?为什么我们选择使用$link而不是var链接?

Q3> why we use $link here? why we choose to use $link rather than var link?

<script>
$(window).scroll(function() {
  $link = $('nav a[hash=#first]');
  $link.addClass('selected');
});
</script>

谢谢

推荐答案

Q1.是的,没有.达到jQuery之后,也许jQuery仍会做一些事情,但是,如果您只是想查找先前在主体中加载的元素,它将起作用.

Q1. Yes and no. Perhaps jQuery will still do a few things after the has been reached, but if you are just trying to find a element that was loaded previously in the body it will work.

Q2.它创建一个指向窗口的jQuery对象.它不是jQuery选择器,$(document)或$(document.body)都不是-在这些中,您是将节点传递给jQuery而不是Selector.

Q2. It creates a jQuery Object pointing to the window. It is not a jQuery Selector, neither is $(document) or $(document.body) - in these you are passing a node to jQuery and not a Selector.

Q3.它缓存它.通过执行$link = $('nav a[hash=#first]');,我们将结果缓存/分配给$ link,就像我们做了两次$('nav a[hash=#first]')一样,然后jQuery将不得不两次查找该结果-如果未缓存所有调用,这将变得非常密集.您还应该使用var $link = $('nav a[hash=#first]');,以确保未全局定义$link,因为这很糟糕(由于变量冲突).

Q3. It caches it. By performing $link = $('nav a[hash=#first]'); we cache/assign the result to $link, as if we did $('nav a[hash=#first]') twice, then jQuery would have to find that result twice - this could become/will become quite intensive if all your calls are not cached. You should also be using var $link = $('nav a[hash=#first]');, to ensure that $link is not defined globally - as that is bad (due to variable conflicts).

作为一般惯例;使用DOM元素的所有内容都应在文档准备就绪后(以确保已加载它们,并且jQuery准备使用它们),而其他不应该的(因为无需等待).

As a general practice; anything which uses DOM elements should be after document ready (to ensure they have loaded and jQuery is ready to use them), anything that doesn't shouldn't (as there is no need for the wait).

这篇关于jQuery-是否需要$(document).ready?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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