首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

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

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

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

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>
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!});
或者,使用我们在之前的代码中学到的更加简短的语法:

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

热点排行