$与jQuery [英] $ versus jQuery
问题描述
我们正在从MooTools切换到jQuery.我有一个同事告诉我,在使用jQuery方法时(如果我正确理解他的话)不要使用$
作为前缀.他说,相反,更合适或更安全的方法(我没有真正关注他)是使用jQuery.
.
We're switching from MooTools to jQuery at work. I have a coworker that told me never to use $
as the prefix when using a jQuery method (if I understood him correctly). He said that instead, the more appropriate or safer way (I didn't really follow him) was to use jQuery.
.
因此,例如,应该使用jQuery.plugin()
代替$.plugin()
.
So instead of $.plugin()
, jQuery.plugin()
should be used, for example.
为什么会这样呢?他与$
/jQuery
有什么区别?我应该忘记美元符号作为我的访问者吗?仅在某些情况下?
Why would that be the case? What distinction is he making with $
/jQuery
? Should I forget about the dollar sign as my accessor? Only in certain circumstances?
推荐答案
为什么会这样呢?他的$/jQuery区分正确吗?
Why would that be the case? Is his $/jQuery distinction correct?
因为几乎每个JavaScript库都定义了一个称为$的函数.当您在一个文档中有许多库时,可能会出现冲突.如果您确定jQuery并将始终是定义该函数的唯一脚本,那么我不会反对使用$.
Because almost every JavaScript library defines a function called $. When you have many libraries in one document, conflicts may appear. If you are sure that jQuery is and always will be the only script defining that function, I wouldn't have anything against using $.
jQuery定义了解决冲突的好方法: jQuery.noConflict .通过使用此函数,您可以定义自己的名称,从而可以访问jQuery,例如
jQuery defines a nice solution to resolve conflicts: jQuery.noConflict. By using this function you can define your own name, whereby jQuery will be accessible, e.g.
var $jq = jQuery.noConflict(true);
调用此函数将导致在初始化jQuery之前恢复$和jQuery变量的先前值.我不记得是否还有其他库尝试解决名称冲突.
Calling this function will result in restoring previous values for $ and jQuery variables when existed before initializing jQuery. I don't remember if any other libraries try to resolve name conflicts.
如果您想一直使用$而不是jQuery,则可以在一个单独的私有范围内运行代码,该范围通过使用自调用函数来保存$的定义.
If you want to use $ instead of jQuery all the time you can run your code in a separate, private scope that holds the definition of $ by using a self-invoking function.
(function($){
// your code goes here
$("body").append("<p>Hello World!</p>");
})(jQuery); // or even jQuery.noConflict()
这篇关于$与jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!