jQuery技巧:保证你的代码安全

在多人合作开发中一定要确保变量,对象,函数等命名不要冲突:
方法一:当别人使用了其他的js库,并该库使用了”$”变量,那么我们可以使用noConflict()方法:

 
1var j = jQuery.noConflict();
2// Now, instead of $, we use j.
3j('#someDiv').hide();
4  
5// The line below will reference some other library's $ function.
6$('someDiv').style.display = 'none';

方法二,把你的代码放在一个匿名函数里面,然后把jQuery作为参数传递给它,那么在这个函数体中的$是不会影响外面或者被外面影响的。

 
1(function($) {
2// Within this function, $ will always refer to jQuery
3})(jQuery);

方法三,通过ready方法传递$

 
1jQuery(document).ready(function($) {
2// $ refers to jQuery
3});
4// $ is either undefined, or refers to some other library's function.

或者使用简写:

 
1$(function() {
2// let's get up in heeya
3});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值