Sometimes you want to make a piece of functionality available throughout your code. For example, perhaps you want a single method you can call on a jQuery selection that performs a series of operations on the selection. In this case, you may want to write a plugin.

linkHow jQuery Works 101: jQuery Object Methods

Before we write our own plugins, we must first understand a little about how jQuery works. Take a look at this code:


$( "a" ).css( "color", "red" );

This is some pretty basic jQuery code, but do you know what's happening behind the scenes? Whenever you use the $ function to select elements, it returns a jQuery object. This object contains all of the methods you've been using (.css(), .click(), etc.) and all of the elements that fit your selector. The jQuery object gets these methods from the $.fn object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well.

linkBasic Plugin Authoring

Let's say we want to create a plugin that makes text within a set of retrieved elements green. All we have to do is add a function called greenify to $.fn and it will be available just like any other jQuery object method.


$.fn.greenify = function() {



    this.css( "color", "green" );



};



 



$( "a" ).greenify(); // Makes all the links green.

Notice that to use .css(), another method, we use this, not $( this ). This is because our greenify function is a part of the same object as .css().

linkChaining

This works, but there are a couple of things we need to do for our plugin to survive in the real world. One of jQuery's features is chaining, when you link five or six actions onto one selector. This is accomplished by having all jQuery object methods return the original jQuery object again (there are a few exceptions: .width() called without parameters returns the width of the selected element, and is not chainable). Making our plugin method chainable takes one line of code:


$.fn.greenify = function() {



    this.css( "color", "green" );



    return this;



}



 



$( "a" ).greenify().addClass( "greenified" );

linkProtecting the $ Alias and Adding Scope

The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that $ is an alias to the jQuery function. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $:


(function ( $ ) {



 



    $.fn.greenify = function() {



        this.css( "color", "green" );



        return this;



    };



 



}( jQuery ));

In addition, the primary purpose of an Immediately Invoked Function is to allow us to have our own private variables. Pretend we want a different color green, and we want to store it in a variable.


(function ( $ ) {



 



    var shade = "#556b2f";



 



    $.fn.greenify = function() {



        this.css( "color", shade );



        return this;



    };



 



}( jQuery ));

linkMinimizing Plugin Footprint

It's good practice when writing plugins to only take up one slot within $.fn. This reduces both the chance that your plugin will be overridden, and the chance that your plugin will override other plugins. In other words, this is bad:


(function( $ ) {



 



    $.fn.openPopup = function() {



        // Open popup code.



    };



 



    $.fn.closePopup = function() {



        // Close popup code.



    };



 



}( jQuery ));

It would be much better to have one slot, and use parameters to control what action that one slot performs.


(function( $ ) {



 



    $.fn.popup = function( action ) {



 



        if ( action === "open") {



            // Open popup code.



        }



 



        if ( action === "close" ) {



            // Close popup code.



        }



 



    };



 



}( jQuery ));

linkUsing the each() Method

Your typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections. If you want to do any manipulating with specific elements (e.g. getting a data attribute, calculating specific positions) then you need to use .each() to loop through the elements.


$.fn.myNewPlugin = function() {



 



    return this.each(function() {



        // Do something to each element here.



    });



 



};

Notice that we return the results of .each() instead of returning this. Since .each() is already chainable, it returns this, which we then return. This is a better way to maintain chainability than what we've been doing so far.

linkAccepting Options

As your plugins get more and more complex, it's a good idea to make your plugin customizable by accepting options. The easiest way to do this, especially if there are lots of options, is with an object literal. Let's change our greenify plugin to accept some options.


(function ( $ ) {



 



    $.fn.greenify = function( options ) {



 



        // This is the easiest way to have default options.



        var settings = $.extend({



            // These are the defaults.



            color: "#556b2f",



            backgroundColor: "white"



        }, options );



 



        // Greenify the collection based on the settings variable.



        return this.css({



            color: settings.color,



            backgroundColor: settings.backgroundColor



        });



 



    };



 



}( jQuery ));

Example usage:


$( "div" ).greenify({



    color: "orange"



});

The default value for color of #556b2f gets overridden by $.extend() to be orange.

linkPutting It Together

Here's an example of a small plugin using some of the techniques we've discussed:


(function( $ ) {



 



    $.fn.showLinkLocation = function() {



 



        this.filter( "a" ).each(function() {



            var link = $( this );



            link.append( " (" + link.attr( "href" ) + ")" );



        });



 



        return this;



 



    };



 



}( jQuery ));



 



// Usage example:



$( "a" ).showLinkLocation();

This handy plugin goes through all anchors in the collection and appends the href attribute in parentheses.


<!-- Before plugin is called: -->



<a href="page.html">Foo</a>



 



<!-- After plugin is called: -->



<a href="page.html">Foo (page.html)</a>

Our plugin can be optimized though:


(function( $ ) {



 



    $.fn.showLinkLocation = function() {



 



        this.filter( "a" ).append(function() {



            return " (" + this.href + ")";



        });



 



        return this;



 



    };



 



}( jQuery ));

We're using the .append() method's capability to accept a callback, and the return value of that callback will determine what is appended to each element in the collection. Notice also that we're not using the .attr() method to retrieve the href attribute, because the native DOM API gives us easy access with the aptly named href property.

How to Create a Basic Plugin的更多相关文章

  1. How to Create a Basic Plugin 如何写一个基础的jQuery插件

    How to Create a Basic Plugin Sometimes you want to make a piece of functionality available throughou ...

  2. jquery ----> How to Create a Basic Plugin (翻译)

    http://learn.jquery.com/plugins/basic-plugin-creation/ 如何创建一个基本的插件 有时候你想在整个代码中提供一些功能. 例如,也许你想要一个单一的方 ...

  3. jQuery-How to Create a Basic Plugin

    官方插件:http://learn.jquery.com/plugins/basic-plugin-creation/ $.extend方法和$.fn.extend方法都可以用来扩展jQuery功能. ...

  4. Create a Basic Shader in Shader Forge

    [Create a Basic Shader in Shader Forge] 1.打开ShaderForge.Window-> Shader Forge.(打开速度较慢) 2.通过NewSha ...

  5. [转]create a basic sql server 2005 trigger to send email alerts

    本文转自:http://blog.netnerds.net/2008/02/create-a-basic-sql-server-2005-trigger-to-send-e-mail-alerts/ ...

  6. Eclipse:Could not create the view: Plug-in org.eclipse.jdt.ui was unable to load class org.eclipse.

    今天电脑死机了2次,重启电脑开eclipse后,发现项目环境坏了.百度后得到的答案是删除.metadata目录.但觉得麻烦,后在stackoverflow发现最佳的方式是 把 .metadata/.p ...

  7. jQuery 插件基础

    jQuery 插件基础 翻译 How to Create a Basic Plugin 如果你需要在 jQuery 选择器上执行一系列重复操作, 这时候你需要编写 jQuery 插件. jQuery ...

  8. 解决了jQuery插件未能导入到项目之中

    Loading jQuery plugins from third-party scripts <script src="js/jquery.js" type="t ...

  9. 掌握jQuery插件开发

    进行jQuery插件开发前,首先要知道两个问题:什么是jQuery插件?jQuery插件如何使用? 第一个问题,jQuery插件就是用来扩展jQuery原型对象的一个方法,简单来说就是jQuery插件 ...

随机推荐

  1. Unity中Shader和AssetBundle结合使用的注意事项

    之前遇到了一件事情就是打包安卓的ab后,unity在editor启动下,加载出来的abshader丢失,其实发布安卓后运行是正常的,当时还纠结了半天,还写了个重新赋值的脚本 下面是unity开发的一些 ...

  2. 你还在把Java当成Android官方开发语言吗?Kotlin了解一下!

    导语:2017年Google IO大会宣布使用Kotlin作为Android的官方开发语言,相比较与典型的面相对象的JAVA语言,Kotlin作为一种新式的函数式编程语言,也有人称之为Android平 ...

  3. package.json中dependencies 和devDependencies的差异

    我们在日常开发中,经常会使用到npm安装对应的包,会经常在package.json中看到dependencies 和devDependencies 二者的区别: devDependencies:是你开 ...

  4. Redis简介及持久化

    Redis是一个key-value数据库,他不仅性能强劲,而且还具有复制特性以及为解决问题而生的独一无二的数据模型.可用于缓存.消息队列.发布.订阅消息.商品列表和评论列表等场景.Redis提供了5种 ...

  5. [LeetCode]21. Merge Two Sorted Lists合并两个有序链表

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...

  6. java常用API之基本类型包装类

    基本类型包装类概述: 在实际程序使用中,程序界面上用户输入的数据都是以字符串类型进行存储的. 而程序开发中,我们需要把字符串数据,根据需求转换成指定的基本数据类型. 想实现字符串与基本数据之间转换,需 ...

  7. js原生拖拽

    style样式 <style type="text/css"> #box{ width: 100px; height: 100px; background: deepp ...

  8. canvas玩转微信红包

    CSS3相关属性: <!DOCTYPE html> <html> <head lang='en'> <meta charset='UTF-8'/> &l ...

  9. Java将科学计数法数据转为字符串

    如果Excel单元格数据类型为数值,数字太长会变成科学计数法,Java读取的时候使用如下方法可将其转为字符串 BigDecimal bd = new BigDecimal("3.000085 ...

  10. 内存分配malloc函数注意事项。

    malloc的全称是memory allocation,中文叫动态内存分配,用于向系统申请分配指定字节的内存空间 原型:extern void *malloc(unsigned int num_byt ...