(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>
幸运的是,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 $.
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值