The jQuery site lists the basic plugin syntax for jQuery as this:

(function( $ ){    
  $.fn.myPlugin = function() {      
    // there's no need to do $(this) because
    // "this" is already a jquery object

    // $(this) would be the same as $($('#element'));

    this.fadeIn('normal', function(){    
      // the this keyword is a DOM element    
    });    
  };
})( jQuery );

I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:

  1. 如果替换函数($)...对于一个变量,比如"the_function",语法如下所示:

     (the_function)( jQuery );
    

    What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?

  2. 它以function($)开头.所以它正在创建一个函数,据我所知,这个函数永远不会运行,参数是$,这个参数已经定义了?那里发生了什么事?

Thanks for the help!

推荐答案

function(x){ 
    x...
}

它只是一个没有名字的函数,只接受一个参数"x",并用x做事情.

您可以使用$来代替常见的变量名"x",后者虽然不太常见,但仍然合法.

function($){ 
    $...
}

我将把它放在括号中,以确保它被解析为表达式:

(function($){
    $....
})

To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:

(function($){
    $...
})(3);

为了方便起见,让我们调用这个函数并将jQuery作为变量传入:

(function($){
     $....
})(jQuery);

这将创建一个新函数,该函数接受一个参数,然后调用该函数,并将jQuery作为值传递.

WHY?

  • Because writing jQuery every time you want to do something with jQuery is tedious.

为什么不干脆写$ = jQuery块呢?

  • Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.

Jquery相关问答推荐

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

在 Laravel 中使用 jQuery post 按相关值过滤 Select 选项,如何显示从控制器返回的数据?

我需要在上一个表格单元格中显示计算结果

jQuery 动画滚动

jQuery: Select 属性大于值的所有元素

可以在删除类时反转css动画吗?

lodash debounce 在匿名函数中不起作用

如何获取文档的滚动位置?

如何在 jQuery .each() 的每次迭代之间添加暂停?

为什么 Chrome 会忽略本地 jQuery cookie?

blueimp 文件上传插件中的 maxFileSize 和 acceptFileTypes 不起作用.为什么?

如何使用jQuery在弹出窗口中预览输入类型=文件中的选定图像?

为什么使用 jQuery on() 而不是 click()

禁用 jquery Select 的下拉菜单

从 Select 元素中获取选定的选项

JQuery - 按值查找单选按钮

我可以通过 JavaScript 禁用 CSS :hover 效果吗?

组织 jQuery/JavaScript 代码的最佳方式 (2013)

一起使用 JQuery-Mobile/Phonegap 的正确方法?

如何让 jQuery 等到效果完成?