我想了解jQuery插件语法 [英] I'd like to understand the jQuery plugin syntax

查看:119
本文介绍了我想了解jQuery插件语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery网站列出了jQuery的基本插件语法:

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 );

我只是想从Javascript的角度理解那里发生了什么,因为它没有看起来它遵循我之前看过JS所做的任何语法。所以这是我的问题列表:

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 ,语法如下所示:

  1. If you replace function($)... with a variable, say "the_function", the syntax looks like this:

 (the_function)( jQuery );

什么是(jQuery);在做什么?围绕the_function的括号是否真的有必要?他们为什么在那里?你能提供的另一段代码是否类似?

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?

它以函数($)开头。所以它创建了一个函数,据我所知,它永远不会被运行,参数为$,已经定义了?那里发生了什么?

It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?

感谢您的帮助!

推荐答案

function(x){ 
    x...
}

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

is just a function without a name, that takes one argument, "x", and does things with x.

而不是'x',这是一个常见的变量名,你可以使用$,这是一个不太常见的变量名,但仍然合法。

Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.

function($){ 
    $...
}

我会把它放在括号中以确保它作为表达式解析:

I'll put it in parentheses to make sure it parses as an expression:

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

致电一个函数,你在它后面放入一个参数列表。例如,如果我们想要调用此函数传入3中的值为 $ ,我们会这样做:

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作为变量:

Just for kicks, let's call this function and pass in jQuery as a variable:

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

这会创建一个新函数,它接受一个参数然后调用该函数,传入jQuery作为值。

This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.

为什么?


  • 因为每次想要做某事时都要写jQuery使用jQuery很乏味。

为什么不只是写 $ = jQuery


  • 因为其他人可能已将$定义为其他内容。这可以保证$的任何其他含义都被这个暗示。

这篇关于我想了解jQuery插件语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆