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

How to Create a Basic Plugin

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.

link How 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.

Basic 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().

Chaining

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:

通过return this来实现链式调用

$.fn.greenify = function() {
    this.css( "color", "green" );
    return this;
}

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

Protecting 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 $:

因为不同的插件可能依赖的jQuery版本不同,所以写自己的插件的时候,把jQuery作为参数进行传递【这里还涉及到了iife的概念】

(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.

iife可以允许我们使用自己的私有变量

(function ( $ ) {

    var shade = "#556b2f";

    $.fn.greenify = function() {
        this.css( "color", shade );
        return this;
    };

}( jQuery ));

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

Using 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.

Accepting 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.

这里涉及到了extend的使用,第一个参数是target object,第二个参数是要被合并到target的object。 数组的话,通过key value进行匹配,相同的key的value会被第二个参数里的数值进行覆盖。

Putting 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.

原文地址:https://www.cnblogs.com/chucklu/p/11112604.html

时间: 2024-10-10 00:22:41

How to Create a Basic Plugin 如何写一个基础的jQuery插件的相关文章

写一个Sublime Text 2插件(CSS文件里px单位替换成rem单位)

三年前我就知道了sublime text 不过那时候用DW还是很爽的样子,后来有天想为难自己了,于是用了两年的vim和五笔,最近又觉得这么好编辑器也可以试试,改变一下自己,用一下的,不过由于工作的原因,没有坚持下来,有时候顺手似乎比先进更重要一些. 最近工作都是做一些移动端的页面,而微信的长按出现二维码有个bug,在ios里缩放的页面长按是不会出现"识别二维码"的.所以需要转换一下,不要让页面缩放,要自适应,这个时候就用rem单位来做的会比较好一些,而我的同事之前开发了一个px to

写了一个简单的jquery插件(初恋啊)

用了好久的jquery了,却没有写过插件,今天研究了一个别人的插件和一些文章,总算搞清楚了jquery插件一些写法, 代码写了一个div当鼠标事件发生时的宽高变化情况,基础,代码基础,基础好了,才能研究深入的东西. 1 (function(jQuery){ 2 /* 3 * 插件应该返回一个JQuery对象,以便保证插件的可链式操作. 4 * JQuery插件的机制:jQuery提供了2个用于扩展jQuery功能的方法 5 * jQuery.fn.extend() 6 * jQuery.exte

jquery ----&gt; How to Create a Basic Plugin (翻译)

http://learn.jquery.com/plugins/basic-plugin-creation/ 如何创建一个基本的插件 有时候你想在整个代码中提供一些功能. 例如,也许你想要一个单一的方法,你可以调用一个jQuery selection来对selection执行一系列操作. 在这种情况下,您可能需要编写一个插件. jQuery如何工作101:jQuery对象方法 在我们编写自己的插件之前,我们必须先了解一下jQuery的工作原理. 看看这个代码: 1 $( "a" ).c

写一个简单的JQ插件(例子)

虽然现在 vue angular react 当道啊但是那 JQ还是有一席之地很多很多的小单位啊.其实还会用到 我也放一个例子吧虽然我也不是很肯定有没有人写的比我更好啊但是我相信 我这个还是蛮实用的 话不多说 丢代码 JQ插件标准的封装代码如下,首先需要闭包: <scripttype="text/javascript"> (function ($) {  //这里放入插件代码 })(jQuery); </script> 这是jQuery官方的插件开发规范,这样写

写一个mini的JQuery

(function  () { var _$ = window.$;    var _jQuery = window.jQuery;        var jQuery = window.jQuery = window.$ = function(selector){ return new jQuery.fn.init(selector);    }; jQuery.fn = jQuery.prototype = {        init:function(selector){         

写一个限制上传文件大小和格式的jQuery插件

在客户端上传文件,通常需要限制文件的尺寸和格式,最常用的做法是使用某款插件,一些成熟的插件的确界面好看,且功能强大,但美中不足的是:有时候会碰到浏览器兼容问题.本篇就来写一个"原生态"的jQuery插件,使之能限制上传文件的大小和格式. 首先,写一个名称为checkFileTypeAndSize.js的插件.通过判断当前文件的后缀名是否被包含在预先设置所允许的后缀名数组中,来限制文件格式:通过判断当前文件在IE以及其它浏览器下的尺寸是否大于预先设置所允许的最大文件尺寸,来限制文件大小:

自己写一个jquery

通过阅读jquery原代码, 我们可以模拟写一个简单的jquery 比如常用的 jQuery("div").css("color","red");jQuery("#span1").css("color","green"); 1. jQuery(), 因为是链式调用, 所以返回是一个对象. jQuery = function(selector){ return new jQuery.pro

如何写一个Jquery 的Plugin插件

博客分类: Javascript /Jquery / Bootstrap / Web jQuery配置管理脚本FirebugJavaScript JQuery Plugin插件,如果大家不明白什么是JQuery插件或都不清楚如何编写可以查看其官方的网站:jQuery Authoring Guidelines 好了,下面有一些我觉得想做一个好的插件必须应有的要求: 1.在JQuery命名空间下声明只声明一个单独的名称 2.接受options参数,以便控制插件的行为 3.暴露插件的默认设置 ,以便外

Webpack-源码三,从源码分析如何写一个plugin

经过上一篇博客分析webpack从命令行到打包完成的整体流程,我们知道了webpage的plugin是基于事件机制工作的,这样最大的好处是易于扩展.社区里很多webpack的plugin,但是具体到我们的项目并不一定适用,这篇博客告诉你如何入手写一个plugin,然后分析源码相关部分告诉你你的plugin是如何工作.知其然且知其所以然. 该系列博客的所有测试代码. 从黑盒角度学习写一个plugin 所谓黑盒,就是先不管webpack的plugin如何运作,只去看官网介绍. Compiler和Co