为什么要这样编写 Jquery 代码?
(function ($) {
$(function () {
.......
});
})(jQuery);
最佳答案
这称为闭包,以避免与使用 $
的其他库发生冲突。这样您就可以确保在该函数中使用 $
并将 jQuery
作为参数传递。
(function ($) {
$(function () {
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
来自文档:
it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
This is generally used to author plugins. Read out more here
关于jquery - 为什么要这样写Jquery代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15726850/