目录

jQuery - 插件( Plugins)

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

有很多jQuery插件可以从https://jquery.com/plugins存储库链接下载。

如何使用插件

为了使我们可以使用插件的方法,我们在文件的中包含了与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. 前缀消除了与其他库一起使用的文件的任何可能的名称冲突。

例子 (Example)

以下是一个小插件,具有用于调试目的的警告方法。 将此代码保存在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
↑回到顶部↑
WIKI教程 @2018