jQuery 语法 - 何时使用 $(美元)与 jQuery [英] jQuery syntax - when to use $ (dollar) vs jQuery
问题描述
这两者有什么区别?
$('#SPANID').html("Some Text");
jQuery('#SPANID').html("Some Text");
它是原型还是 jQuery?
Is it something prototype vs jQuery?
推荐答案
他们都做同样的事情.大多数库使用 $ 作为访问库中函数的更短方法.
They both do the same thing. Most Libraries use $ as a shorter way to access functions within the libraries.
jQuery 有多种访问其库的方式:
jQuery has many ways of accessing its library:
window.jQuery('#SPANID').html("Some Text");
window.$('#SPANID').html("Some Text");
jQuery('#SPANID').html("Some Text");
$('#SPANID').html("Some Text");
如果您使用多个库,可以使用 jQuery 或 window.jQuery 代替 $.
jQuery or window.jQuery can be used instead of $ if you were using more than one library.
JQuery 有一个名为 jQuery.noConflict(); 的函数,它放弃了 jQuery 对$ 变量使 $ 不适用于 jQuery.
JQuery has a function called jQuery.noConflict(); which relinquishs jQuery's control of the $ variable making $ not work with jQuery.
这对于使用多个使用 $ 的库很有好处.
This would be good for using more than one library that use $.
所以当你使用 jQuery 你会做 jQuery('#message').addClassName('read');
和 $('#message').addClassName('read');
使用原型时.
So you when you use jQuery you would do jQuery('#message').addClassName('read');
and $('#message').addClassName('read');
when using Prototype.
(下一点有点离题,但如果你想在多个库中使用 $ 会有所帮助)
(This next bit is a little off topic but will help if you want to use $ with multiple libraries)
虽然有一种方法可以同时在不同的库上使用$,使用匿名函数.像这样:
Although there is a way to use $ on different libraries at the same time, using anonymous functions. like so:
(function($){
})(jQuery);
(function($){
})(Prototype);
每个函数都传递库对象,所以 jQuery 和 Prototype,作为变量 $ 允许使用它与许多库一起使用.如果您在每个库中包含每个库的代码,它将起作用.
Each of the functions passes the library object, so jQuery and Prototype, as the variable $ allowing use to use it with many libraries. If you contain your code for each library within each one it will work.
例如:
(function($){
$(document).ready(function(){
$('#message').addClass('read');
});
})(jQuery);
(function($){
document.observe("dom:loaded", function() {
$('message').addClassName('read');
//Or
$$('#message').addClassName('read');
});
})(Prototype);
这篇关于jQuery 语法 - 何时使用 $(美元)与 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!