第一个示例肯定有一个用例。如果您在同一页面上加载了其他 JS 库/脚本,则无法保证它们不会覆盖 $ 变量。 (当您在同一页面上有 Prototype 和 jQuery 时,这很常见)。
因此,如果 Prototype 使用 $,那么您需要在想要使用 jQuery 的任何时候使用 jQuery。这可能会变得非常丑陋:
jQuery(function(){
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
})
请记住,我们不能使用$,因为这是全局范围内的 Prototype 方法。
但是如果你把它包裹在这个里面..
(function($){
$(function(){
// your code here
});
})(jQuery);
$ 实际上会在内部引用 jQuery 库,而在外部仍然引用 Prototype!这可以帮助整理您的代码:
(function($){
$(function{}(
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
));
})(jQuery);
这是 jQuery 扩展的常见模式,以确保它们始终添加到 jQuery 对象中,但可以使用 $ 编写以保持代码整洁。