jQuery - 插件

插件是用标准JavaScript文件编写的一段代码.这些文件提供了有用的jQuery方法,可以与jQuery库方法一起使用.

有很多jQuery插件可以从 https://jquery.com/plugins .

如何使用插件

为了让我们可以使用插件的方法,我们在< head>中包含非常类似于jQuery库文件的插件文件.文档.

我们必须确保它出现在主jQuery源文件之后,以及我们的自定义JavaScript代码之前.

以下示例说明如何包括 jquery.plug-in.js 插件 :

<html>
   <head>
      <title>The jQuery Example</title>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>

      <script src = "jquery.plug-in.js" type = "text/javascript"></script>
      <script src = "custom.js" type = "text/javascript"></script>
      
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            .......your custom code.....
         });
      </script>
   </head>
	
   <body>
      .............................
   </body>
</html>


如何开发插件

编写自己的插件非常简单.以下是创建方法的语法 :

jQuery.fn.methodName = methodDefinition;


这里 methodNameM 是新方法的名称, methodDefinition 是实际的方法定义.

jQuery团队推荐的指南如下 :

  • 任何方法或功能你附加的结尾必须有分号(;).

  • 你的方法必须返回jQuery对象,除非另有说明.

  • 你应该使用this.each来迭代当前匹配元素集 - 它会产生干净且兼容的代码.

  • 使用jquery前缀文件名,然后使用插件的名称加上文件,并以.js结尾.

  • 始终将插件直接附加到jQuery而不是$,所以用户可以通过noConflict()方法使用自定义别名.

例如,如果我们编写一个插件,我们想要命名 debug ,我们这个插件的JavaScript文件名是 :

jquery.debug.js


使用 jquery.前缀消除了任何可能的名称冲突用于其他库的文件.

示例

以下是一个小插件,具有用于调试目的的警告方法.将此代码保存在 jquery.debug.js 文件 :

jQuery.fn.warning = function() {
   return this.each(function() {
      alert('Tag Name:"' + $(this).prop("tagName") + '".');
   });
};


以下是显示warning()方法用法的示例.假设我们将 jquery.debug.js 文件放在html页面的同一目录中.

在线演示

<html>
   <head>
      <title>The jQuery Example</title>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script src = "jquery.debug.js" type = "text/javascript">
      </script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").warning();
            $("p").warning();
         });
      </script>	
   </head>
	
   <body>
      <p>This is paragraph</p>
      <div>This is division</div>
   </body>
</html>


这会提醒您以下结果 :

This is paragraph
This is division