当前位置: 首页 > 编程日记 > 正文

如何创建一个基础jQuery插件

如何创建一个基础插件

How to Create a Basic Plugin

有时你想使一块功能性的代码在你代码的任何地方有效.比如,也许你想调用jQuery对象的一个方法,对该对象进行一系列的操作.可能你写了一个真正有用的实用函数,想它能够轻易的移植到其他项目.在这种情况下,你可能想写一个插件.

  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 perfroms a series of operations on the selection. Maybe you wrote a really useful utility function that you want to be able to move easily to other projects. In this case, you may want to write a plugin.

jQuery是如何工作的 101:jQuery 对象方法和实用方法

How jQuery Works 101:jQuery Object Methods and Utility Methods

在我们写我们自己的插件之前, 我们必须先对jQuery如何工作有一些了解.请看看这段代码:

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

这是一段简单的jQuery代码,但是你知道在幕后发生了什么吗?每当你使用 $ 函数来选择元素,他会返回一个jQuery对象.这个对象包含了所有你以前使用过的方法(.css(), .click() 等等)和适合你的选择器的所有元素.jQuery对象从 $.fn 对象获取这些这些方法.这个对象包含了所有jQuery对象的方法,如果我们想写我们自己的方法,它也必须包含在内.

  This is some pretty basic jQuery code, but do you know what's happning 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.

此外jQuery实用函数 $.trim() 用来删除用户输入前后的空白符.实用方法是直接属于 $ 函数本身的.当jQuery API没有对你检索到的DOM元素组实现预期功能时,你也许有时想写一个实用函数插件对其进行扩展.

  Additionally the jQuery utility method $.trim() it used above to remove any leading or trailing empty space characters from the user input. Utility methods are functions that reside directly in the $ function itself. You may occasionally want to write a utility method plugin when your extension to the jQuery API does not have to do something to a set of DOM elements you've retrieved.

基本插件创作

Basic Plugin Authoring

比如说我们想创建一个使检索到的元素变绿的插件.我们要做的就是在 $.fn 中添加一个名为 greenify 的函数,它会像其他jQuery对象函数一样有效.

  Let's say we want to create a plugin that makes test 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();

注意使用 .css() 和其他类似方法时,我们用 this 而不是 $(this).这是因为我们的 greenify 函数和 .css() 是同一个对象的一部分.

Notice that 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

它工作了,但是实际上我们会有几件事情要做,jQuery的特性之一就是连贯性,当你链接了四到五个动作到一个选择器.这是通过所有的 jQuery 对象方法再次返回源 jQuery 对象来实现的(这里有一些例外: 无参数调用 .width() 返回选中元素的宽度, 它是没有连贯性的).使我们的插件方法具有连贯性需要一行代码:

  This works, but there's a couple of things we need to do for our plugin to survive in the reeal 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 few exceptions: .width() called without parameters return 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");

值得注意的是连贯性的概念在类似 $.trim() 的 jQuery 实用函数上不适用.

  Note that the notion of chaining is not applicable to jQuery utility methods like $.trim().

保护$别名和添加范围

Protecting $ Alias and Adding Scope

变量$在JavaScript库中非常受欢迎,如果你在使用jQuery的同时使用其他的库,你应使用jQuery.noConflict()来使jQuery不使用$.然而,假设$是jQuery函数的别名将损坏我们的插件.我们需要将我们所有的代码放进一个立即调用函数表达式里面, 然后传递函数jQuery,命名为参数$:

  The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have 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 $:

(funtion($){$.fn.greenify = function(){this.css("color", "green");return this;}$.ltrim = function(str){return str.replace(/^\s+/, "");}$.rtrim = function(str){return str.replace(/\s+$/, "");}
}(jQuery));

并且,立即调用函数表达式的主要作用是允许我们拥有自己的私有变量.假设我们想添加一个不同的颜色,而且我们想将它保存在一个变量里面.

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

(function($){var shade = "#556b2f";$.fn.greenify = function(){this.css("color", shade);return this;}
}(jQuery));

Minimizing Plugin Footprint

好的惯例是写一个插件只占用 $.fn 的一个接口,这段代码可能导致你的插件被其他的插件覆盖,也可能导致你的插件覆盖了其他插件,换句话说,这是段糟糕的代码:

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

使用 each() 方法

Using the each() Method

你的典型的jQuery对象可能包含任意数量的DOM元素,这也是为什么经常把jQuery对象称为集合的原因.如果你想对特定的元素进行一些操作(例如:读取属性, 计算特定位置),那么你需要使用 .each() 来遍历这些元素.

  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.});
}

注意我们返回 .each() 代替返回 this. 因为 .each() 已经是具有连贯性的,它的返回值是 this.在我们曾经做过的事中,到目前为止,这是一个维护可连续性更好的办法.

  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

当你的插件越来越复杂,好的主意是通过接受一些选项来使你的插件可定制.最简单的做到这一点的办法是一个字面对象,特别是有很多的选项.让我们修改我们的greenify插件以接受一些选项.

  As your plugins get more and more complex, it's a good idea to make your plugin customizable by accepting options. The easiest way 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 optionvar settings = $.extend({//These are the defaults.color: "#55b62f",backgroundColor: "white"}, options);//Greenify the collection based on the settingsreturn this.css({color: setting.color,backgroundColor: setting.backgroundColor});};
}(jQuery));//Example usage:$("div").greenify({color: "orange"
});

color 的缺省值 #556b2f 被 $.extend() 覆盖为 orange.

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

把它们放在一起

Putting It Together

这里是一个使用了一些我们已经讨论过的技巧的小插件例子:

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

(function($){$.fn.showLinkLocation = function(){return this.filter("a").each(function(){$(this).append(" (" + $(this).attr("href") + ")");});};
}(jQuery));//Example usage:$("a").showLinkLocation();

这个易用的插件遍历集合中所有的链接然后把href属性放在括弧中添加在元素后面.

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

我们的插件可以通过以下代码优化:

  Our plugin can be optimized though:

(function($){$.fn.showLinkLocation = function(){return this.filter("a").append(function(){return " (" + this.href + ")";})};
}(jQuery));

我们使用的是 .append() 方法的接受回调函数的能力,返回值将决定集合中的每个元素的尾部添加什么.注意我们不是使用 .attr() 方法来检索href属性,因为原生的DOM API给了我们适当命名的href属性方便使用.

  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/brokenjar/p/basic-plugin-creation.html

相关文章:

rk3399在linux机上烧写img,烧写固件 — TB-96AI documentation

Window主机烧写固件1、安装Windows PC端USB驱动(首次烧写执行)。2、双击DriverAssitant_v4.5DriverInstall.exe打开安装程序,点击“驱动安装”按提示安装驱动即可,安装界面如下所示:3、Type-C线连接主机端的USB接口和RK3399Pro TB-96AI开发板的Type-C接口…

Eclipse,Mycclipse自动补全快捷键设置

为什么80%的码农都做不了架构师?>>> eclipse3.3及以后的版本中中把内容助手(content assist)的快捷键由 alt /改成了ctrl space,这又刚好跟我们操作系统的切换输入法的快捷键冲突,所以造成内容助手不能使用了,给写代…

php 无限极分类

无限极分类1&#xff1a; 1 public function judeg($id)2 {3 $rs Db::name(finance_class) -> field(parent_code) -> where(id,$id) -> select();4 $i 1;5 foreach($rs as $k > $v){6 if($v[parent_code] <> 0){7 $i $this -…

ceph-bluestore-tool基本使用

主要是在bluestore的实例上执行低级管理操作的使用程序,是ceph bluestore的管理工具 命令 help显示帮助信息fsck [--deep]对bluestore元数据进行一致性检查。如果指定了–deep,还要读取所有对象数据并验证校验和repair运行一致性检查 并修复我们可以发生的任何错误bluefs-expo…

Android基础是什么,Android基础概念

android {compileSdkVersion 23buildToolsVersion “23.0.1”defaultConfig {applicationId “com.example.checkyourtargetsdk"minSdkVersion 15targetSdkVersion 23versionCode 1versionName “1.0”}以上是Android工程里名称为app的module的build.gradle文件其中的内容…

HDOJ 1060 Leftmost Digit

Author Ignatius.L题目大意&#xff1a;1.第一行输入一个整数T代表接下来有T组测试数据。2.接下来的T行&#xff0c;每行输入一个整数&#xff08;1<N<1,000,000,000&#xff09;。3.输出结果为N^N&#xff08;N的N次方&#xff09;最左边的那一位数&#xff08;即最高位…

WPF-002 下拉列表的简单实现

最近在一个WPF项目中用到一个下拉列表&#xff0c;随着用户输入字符而进行显示&#xff0c;使用了绑定等知识&#xff0c;虽然实现比较简单&#xff0c;可是在性能上也是想了很多办法终于才勉强可以用&#xff0c;与大家分享下。 用于页面绑定的模型类&#xff1a; public clas…

洛谷:P3950 部落冲突

原题地址:https://www.luogu.org/problemnew/show/P3950 题目简述 给定一棵树&#xff0c;每次给定一个操作&#xff0c;有如下两种&#xff1a; 将某条边染黑 2.询问给定的u,v两点间是否有边被染黑思路 询问两点间是否有边被染黑只需要在求LCA时判一下就行。所以直接上树链剖分…

深入理解ceph-disk prepare 源码逻辑

文章目录CEPH-DISK代码逻辑DEF MAIN:DEF PARSE_ARGS:DEF Prepare.set_subparser(subparsers)def _prepare(self):PrepareBluestore的_prepare函数def prepare(self, *to_prepare_list):PrepareData类中的prepare函数def prepare_device(self, *to_prepare_list): #prepare_devi…

Deep Learning 学习随记(三)续 Softmax regression练习

上一篇讲的Softmax regression&#xff0c;当时时间不够&#xff0c;没把练习做完。这几天学车有点累&#xff0c;又特别想动动手自己写写matlab代码 所以等到了现在&#xff0c;这篇文章就当做上一篇的续吧。 回顾&#xff1a; 上一篇最后给出了softmax regression的代价函数和…

html画三个重叠的矩形,html5 实现两个矩形的叠加

Canvas Primer - Example: Drawing shadowswindow.addEventListener(load, function () {//得到canvas&#xff0c;并检测是否支持canvasvar elem document.getElementById(myCanvas);if (!elem || !elem.getContext) {return;}// 得到可以画图的上下文contextvar context el…

sqlplusw下登录sys账户

今天使用sqlplusw时&#xff0c;发现每次使用sys用户登录时总是报错&#xff0c;提示要以sysdba或者sysoper的身份登录&#xff0c;错误提示如下图所示&#xff1a;可是界面上没地方可以输入角色的地方呀&#xff0c;后经尝试发现&#xff0c;在口令输入框里首先输入密码&#…

mybatis =或这个=提示错误Tag name expecte问题解决

解决方案&#xff1a; 1、将<号或者>号进行转义 DATE_SUB(CURDATE(), INTERVAL 31 DAY) < DATE(created) 2、使用<![CDATA[ ]]>符号进行说明 <![CDATA[DATE_SUB(CURDATE(), INTERVAL 31 DAY) < DATE(created)]]> 附&#xff1a; 附录&#xff1a;常见…

s-sgdisk源码分析 “--set-alignment=value分区对齐参数”

文章目录边界对齐子命令使用源码分析sgdisk.cc main函数入口gptcl.cc DoOptions解析并执行具体命令函数gpt.cc CreatePartition创建分区函数&#xff0c;设置起始扇区对齐gpt.cc Align分区对齐函数&#xff0c;设置起始扇区对齐sgdisk命令是由 gdisk-0.8.6-4.el7.x86_64程序包安…

NuGet学习笔记(3) 搭建属于自己的NuGet服务器

文章导读 创建NuGetServer Web站点 发布站点到IIS 添加本地站点到包包数据源 在上一篇NuGet学习笔记(2) 使用图形化界面打包自己的类库 中讲解了如何打包自己的类库&#xff0c;接下来进行最重要的一步&#xff0c;从零开始搭建属于自己的NuGet服务器&#xff0c;诚然园子里及其…

计算机网络共享打不开,网络和共享中心打不开,共享无法访问没有权限

在Win7系统下如果别的计算机设置了共享&#xff0c;那么在本机设置网络发现后就可以打开网络搜索到共享计算机和共享文件了&#xff0c;不过一些朋友反馈win7系统网络发现无法启用的问题&#xff0c;下面小编整理了解决方法&#xff0c;大家可以参考一下哦。解决方法如下&#…

千万不要把 bool 当成函数参数

我们有很多 Coding Style 或 代码规范。 但这一条可能会经常被我们所遗忘&#xff0c;就是我们 经常会在函数的参数里使用bool参数&#xff0c;这会大大地降低代码的可读性。 不信&#xff1f;我们先来看看下面的代码。 当你读到下面的代码&#xff0c;你会觉得这个代码是什么意…

修改ceph-disk源码,增加指定ceph.conf部署osd的功能

文章目录 ceph环境源码修改 主文件:`ceph-disk/main.py`main函数入口parse_args(argv)增加子命令解析get_conf函数使`conf`生效修改所有调用get_conf函数的上级函数参数配置由于最近工作中需要优化osd部署流程,单节点并发加盘过程需要指定特定conf文件,来完成单盘db,wal分区…

相关计算机专业的英语文献,英文文献及翻译计算机专业.doc

英文文献及翻译计算机专业外文资料翻译—英文原文NET-BASED TASK MANAGEMENT SYSTEMHector Garcia-Molina, Jeffrey D. Ullman, Jennifer WisdomABSTRACTIn net-based collaborative design environment, design resources become more and more varied and complex. Besides c…

作业 3 应用分支与循环结构解决问题 统计字符个数

/*统计字符&#xff0c;包括空格或回车&#xff0c;数字字符和其他字符*/#include<stdio.h> int main(void) {int digit,space,letter,other; /*定义4个变量分别存放统计结果*/ char ch;int i;digitspaceletterother0; /*置…

php后期静态绑定

从php5.3开始&#xff0c;php增加了一个叫后期绑定的功能&#xff0c;用于在继承范围内引用静态调用的类 该功能从语言内部角度考虑北命名为“后期静态绑定”&#xff1b;“后期绑定”意思说&#xff1a;static&#xff1a;&#xff1a;不再被解析为定义当前方法所在的类&#…

pytest 9 pytest-datadir读取文件信息

安装&#xff1a;pip install pytest-datadir 介绍&#xff1a;用于操作测试数据目录和文件的插件。pytest-datadir他会寻找包含测试模块名字的文件夹或者全局的一个文件夹名字为data下的数据。比如以下的一个结构&#xff1a; firstdemo.py可以从test_firstdemo文件夹下的文件…

深入理解ceph-disk activate 源码逻辑

文章目录CEPH-DISK代码逻辑Activate osd的主要逻辑如下DEF main_activate激活osd的入口函数DEF mount_activate挂载临时目录&#xff0c;分配osd id并初始化osdDEF activate 分配osd_id以及初始化osdCEPH-DISK代码逻辑 本文在上文 :深入理解ceph-disk prepare 源码逻辑基础上描…

simple_html_dom meta,HTML DOM Meta content 属性

HTML DOM Meta content 属性Meta 对象定义和用法content 属性可设置或者返回 meta 元素 content 属性值。content 属性指定了 meta 信息的内容。注意&#xff1a; 这个属性可用的值依赖于name 和httpEquiv 属性的值。语法设置 content 属性&#xff1a;linkObject.content"…

struts2登录后返回登录前的页面

在Action中添加 String getUrl&#xff08;&#xff09; &#xff5b; return ServletActionContext.getRequest().getHeader("referer"); &#xff5d; 然后配置struts的这个Action的result为&#xff1a;<result type"redirect">${url}</resu…

Exchange 2010 恢复误删除的邮箱账户及其邮箱

在误删除邮箱后&#xff0c;AD中相应的账号也会随之删除&#xff0c;此时该如何恢复&#xff1f; 先来模拟邮箱被误删除&#xff0c;在EMC控制台中删除别名为jqq的邮箱 打开ADUC&#xff0c;发现相应的jqq账号也被删除了: 1.恢复AD账号 下载运行ADRecycle Bin&#xff0c;点击【…

Python 函数初识 (1)

一、今日主要内容 认识函数 函数:对功能或者动作的封装(定义) 语法: def 函数名字(形参) 函数体 函数的调用格式:函数名(实参) 函数的返回值 关键字:return 终止函数的运行 1、函数内部不写return,默认函数末尾返回…

python的popen函数

最近了解了一下python的popen函数的使用&#xff0c;主要是用来执行linux命令 函数使用 使用之前需要导入import os模块 使用方式: os.popen(cmd)返回值: 返回一个文件句柄 import os cmd"/sbin/partx /dev/sdb" result_listos.popen(cmd) print result_list执行…

计算机竞赛CCC可以直接学吗,CCC 计算机竞赛到底有多牛!

加拿大计算机竞赛是什么&#xff1f;难度情况&#xff1f;加拿大计算机竞赛是由加拿大滑铁卢大学主办的&#xff0c;每年举办一次&#xff0c;是一场面向中学生的计算机程序设计比赛&#xff0c;CCC竞赛的一个目的是为广大中学生朋友们提供一个机会来测试自己分析、设计以及编程…

PHP basename() 函数

定义和用法 basename() 函数返回路径中的文件名部分。 语法 basename(path,suffix) 参数描述path必需。规定要检查的路径。suffix可选。规定文件扩展名。如果文件有 suffix&#xff0c;则不会输出这个扩展名。转载于:https://www.cnblogs.com/wuyou/p/3387079.html