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

查看:20
本文介绍了我想了解 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. 如果你将 function($)... 替换为一个变量,比如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天全站免登陆