开发者

jQuery(selector) or $(selector), which one?

Which is better way to use jQuery()? I've heard that jQuery(element) doesn't ruin code in e.g. Wordpress. But $ is easier and faster to w开发者_开发技巧rite.

Which one do you prefer and why?


My order of preference is $(), then var $jq = jQuery.noConflict(); $jq(), then finally jQuery(). You can also limit the scope of the $ function by doing:

;(function($){
    ...in here $ means jQuery...
})(jQuery);

That is create an anonymous function with a parameter of $, pass in jQuery as the parameter and within the function the parameter scope overrides any globally scoped $ function. The latter is most useful when creating plugins yourself.


It just depends on what you need to do, they're both identical.

If you're using another library like Prototype (which also uses $), you'll need to us jQuery, but in most cases where there is no clash, just use $()


The $ shorthand is also used by other frameworks (like prototype), so if you're not using that, feel free to use $ for shorthand. The two are just aliases of each other as far as I know.


For your own extensions that use $ only to call jQuery, you can also use the standard trick of wrapping your code like this

(function($) {
   ... your other code using $(selector).moo here ....
})(jQuery);


Most of my jQuery code falls into two categories: plugins and on-page-load stuff.

For plugins, here's the easiest way:

(function($) {
    $.fn.myplugin = function() { ... };
})(jQuery);

For on-page-load stuff, which is most of it, just do this:

jQuery(function($) {
    $('a[href$="foo"]').click( ... );
});

This way, it doesn't matter at all if there's extra libraries included (eg: Prototype), and you can still use $ instead of typing out "jQuery" each time.


You can use var jq=jQuery.noConflict(); to deal with name conflicts.

Ex:

var $jq=jQuery.noConflict();
$jq("p").hide();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜