jQuery 和 $ 问题

jQuery and $ problems

这看起来很简单,但实际上没有人用简单的英语告诉它如何以及何时工作(至少在前几个搜索引擎的页面中没有)。也许我只是不太擅长寻找正确的关键字。

我已经写了将近 1000 行 jQuery & 我开始认为,如果我写得更多,只会带来更多麻烦,因为我可能会解决所有问题(非常非常轻的 OCD [不是真的但我喜欢顺序] - 代码应该是干净的 & "correct").

如果我将我的代码放在 jQuery(function($) { 中,它将允许我以 $ 开始所有内容,否则我将得到“$ is not a function”错误。

我也注意到有些代码最后有 (jQuery)

有人可以告诉我规则吗?如果采取不同的做法是否有任何影响?

您 运行 遇到的问题似乎很简单:jQuery 可能与 noConflict() 一起使用,这意味着 $ 不会出现在全局中命名空间。为了克服这个问题,您可以删除对上述方法的调用或将您的代码包装在匿名函数中:

(function ($) {
    //Your code
})(jQuery);

这通常发生在 jQuery 库设置为 jQuery.noConflict() 时。为什么会发生这种情况的一个例子是 Wordpress 这样的情况,这样做是为了防止与其他 Wordpress 库的兼容性问题。

如果您想在 jQuery 对象可用后立即使用 $ 作为 jQuery 对象的别名:

(function($) {
    // The locally-scoped $ can be used in this function as an alias to jQuery
})(jQuery);

如果您想使用 $ 作为具有 .ready() 功能的 jQuery 对象的别名:

jQuery(document).ready(function($) {
    // The locally-scoped $ can be used in this function as an alias to jQuery
});

更新:根据您在评论中的问题,是的,您可以像这样将 $(document).ready() 包装在 jQuery(function($) { }) 中:

jQuery(function($) {        
    $(document).ready(function() {
        alert('in .ready() using $');
    });
});

为了使示例更全面,另请参阅当 jQuery 使用 .noConflict() 释放 $ 时会发生什么:

jQuery.noConflict();
jQuery(function() {
    // $ is not locally scoped anymore, _
    // and .noConflict() is on, _
    // so the following won't work, _
    // it will return TypeError: $ is not a function
    $(document).ready(function() {
        alert('in .ready() using $');
    });
});

引用material: