(4)事件处理——(6)给.ready()回调函数传递一个参数(Passing an argument to the .ready() callback)

来源:互联网 发布:2017网页游戏数据报告 编辑:程序博客网 时间:2024/06/06 01:10

In some cases, it may prove useful to use more than one JavaScript library on the same page. As many libraries make use of the $identifier (as it is short and convenient), we need a way to prevent collisions between these uses.

在某些场景下,在一个网页上不仅仅使用一个js库可能是很有用的。由于很多库使用$标示符(因为他很短而且很方便),我们需要阻止这些库的冲突。

Fortunately, jQuery provides a method called jQuery.noConflict()to return control of the $identifier back to other libraries. Typical usage of jQuery.noConflict()is as follows:

<script src="prototype.js"></script><script src="jquery.js"></script><script>jQuery.noConflict();</script><script src="myscript.js"></script>
幸运的是,jquery提供了一个叫做jQuery.noConflick()的方法把对$标示符的控制权交给其他的库。jQuery.noConflict()典型的使用方法如下:

<script src="prototype.js"></script><script src="jquery.js"></script><script>jQuery.noConflict();</script><script src="myscript.js"></script>
First, the other library (Prototype in this example) is included. Then, jQuery itself is included, taking over $for its own use. Next, a call to .noConflict()frees up $, so that control of it reverts to the first included library (Prototype). Now in our custom script, we can use both libraries—but whenever we want to use a jQuery method, we need to write jQueryinstead of $as an identifier.

首先,另外一个库被引入(这里用Prototype做例子),然后,jquery自己被引入,拿来$自己使用。接着,调用.noConflict()函数释放$的控制权,于是对$的控制权重新复原到最初被包含的库(Prototype)中。现在我们一般脚本可以使用两个库了,但是无论何时我们想使用一个jquery方法,我们需要写下jQuery作为标示符,而不是$。
The .ready()method has one more trick up its sleeve to help us in this situation. 
The callback function we pass to it can take a single parameter: the jQuery object itself. This allows us to effectively rename it without fear of conflicts, as shown in the following code snippet:
jQuery(document).ready(function($) {// In here, we can use $ like normal!});
Or, using the shorter syntax we learned in the preceding code:
jQuery(function($) {// Code that uses $.});

.ready()方法有不仅仅一个方法帮助我们处理这种场景。我们传递给他的回调函数可以拥有一个参数:jquery对象自己。这允许我们有效地重命名他,而不用担心冲突,正如下面的代码展示的那样:
jQuery(document).ready(function($) {// In here, we can use $ like normal!});
或者,使用我们在之前的代码中学到的更加简短的语法:

jQuery(function($) {// Code that uses $.});

原创粉丝点击