jquery - 为什么要这样写Jquery代码

标签 jquery

为什么要这样编写 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/

相关文章:

javascript - 如何知道某个ip地址浏览了所有链接?

Javascript 全局变量只能在应用程序运行后访问

javascript - Kendo 多选下拉列表不显示值

javascript - 将一些文本放置在 div 后面

javascript - 如何突出显示所选选项卡?

javascript - Jquery UI 自动完成的限制结果

javascript - 如何使用 JavaScript 或 CSS 更改页面上的字符串

jquery - hide() 单选按钮*和*它在 jquery 中的文本标签

php - 使用 AJAX 从 <select> 下拉列表中检索值?

javascript - Fancytree如何选择/取消选择所有克隆节点