jquery has greatly improved our efficiency in writing JavaScript, allowing us to happily write code and make a variety of special effects. In most cases, we are using jquery plugins developed by others, and today we'll look at how to make jquery plugins for our common functions and then manipulate the DOM like jquery.
First, jquery plug-in development quickly get started
1. jquery Plugin Template
With regard to the writing of jquery plugins, we can write jquery plugins by adding a new function to Jquery.fn. The name of the property is the name of your plugin, and its template is as follows:
(function($) { $.fn.function() { //Todo:add your code }}) (JQuery);
Where Myjqplugin is the name of your plugin, function code is your plug-in implementation code.
2. Interacting with the DOM
After giving the plugin a good name, you can write our code below, but before you write it, you have to say the context. Within the scope of the plug-in, the This keyword points to a jquery object. It is easy to misunderstand this, as this usually points to a DOM element when using jquery normally. Do not understand this, will often use $ and wrapped again.
(function($) { function() { ////this.html ("Hello,world"This.click ( function// Note here This is no longer pointing to the jquery element, where this is pointing to the current function object
Here we have to refer to this point problem, for example, we want to implement a function, click on the DOM element, hide the current element, although this point to the JQuery object, but in click, the point of this has changed, Point to the function it is in. So we access the current element in the click Method, we will pass the variable, the implementation method is as follows:
(function ($) {$.fn.myjqplugin = function () {// It is not necessary to use the $ (this) // $ (this) is the same as $ ($ (' #element ')) this.html ("Hello,world" var $this = $ (this); this.click (function () { Span style= "COLOR: #ff6600" >$this.hide (); // Note here This is no longer pointing to the jquery element, where this is pointing to the current function object }); }; }) (JQuery);
We declare the $this variable to hold the This object so that when we need to use the current element, we can use the $this directly. Let's test it with a complete example:
The code for the HTML page is as follows:
<!DOCTYPE html><Html><Head><Title></Title><ScriptSrc= "Jquery.js"Type= "Text/javascript"></Script><ScriptSrc= "1.js"Type= "Text/javascript"></Script></Head><Body><DivId= "Container"Style= "width:800px;height:200px; border:2px #000 solid;padding:20px;font-size:20px; ">hello,world</div ></body><script type= "Text/javascript" > $ ( " #container "). Myjqplugin (); </script></html>
The JS code for the jquery plugin is as follows:
(function($) {$.fn.myjqplugin =function () {this.css ("Color", "red"); // font color is red this.hide (); this.slidedown (200); // first hidden, then Slidedown this = $ (thisthis.click (function () {$this.html ("Thanks,good bye!"); // display information, then fade $ This.fadeout (2000
The function of this plugin is to first let the element drop-down display, and then click on the element to display good-bye message, and then after 2s fade out. Here you can try to use this in the Click event.
Second, the chain operation of jquery
1. Why should I use chain-type operation?
In fact, a chained operation simply adds the return this to the method on the object. Return the object back, of course, the object can continue to invoke the method, so you can chain-operated. So, simply implement one:
Press CTRL + C to copy the code<textarea style="width: 1031px; height: 409.6px; font-family: Courier New; font-size: 12px; line-height: 1.5"></textarea>Press CTRL + C to copy the code
A general explanation:
Save code and the code looks more elegant. For example, if you don't have a chain, you might want to write code like this:
document.getElementById ("Ele"
This code calls two times document.getElementById to get the elements of the DOM tree, which consumes a large number, and writes two lines, and the chain simply writes a line, saving the code ...
But we can also use the cache element ah. Like what:
var ele = document.getElementById ("Ele"
And the two lines are not much more code than the line, and even the corresponding package makes the code more.
The worst thing is that all of the object's methods return the object itself, meaning there is no return value, which is not necessarily appropriate in any environment.
2, then why should we use chain-like operation?
For a better asynchronous experience, JavaScript is a non-blocking language, so instead of blocking, he can't block, so he needs to drive through events, asynchronously, to do something that needs to block the process.
But asynchronous programming is a crazy thing ... It doesn't matter when the runtime is detached, but it's also separate when writing code ...
What are the common asynchronous programming models?
(1) callback function :
The so-called callback function, which means to register a function somewhere in the system, let the system know the existence of the function, and then, later, when an event occurs, call the function to respond to the event.
function Fun (num, callback) { if (num < 0) { alert ("Score cannot be negative, input error!") ); } if (num = = 0) {alert ("The student may not have taken the exam!") "); } else {alert ("Call high-level function handling!") ); SetTimeout (function () {callback ();},
Here callback is the callback function. You can see that callback is called only if NUM is a non-negative number.
But the problem, if we do not look inside the function, we do not know when the callback will be called, under what circumstances to invoke, there is a certain coupling between the code, the process will also produce some confusion.
Although a callback function is a simple and easy-to-deploy way to implement async, it is not good enough from the programming experience.
(2) chain-Asynchronous :
I think the most commendable thing about chained operation is that it solves the problem that the execution flow of asynchronous programming model is not clear. jquery in $ (document). Ready is a great illustration of this idea. Domcontentloaded is an event that most of jquery's operations do not work until the DOM is loaded, but jquery's designers do not treat him as an event, but instead turn to a "select object, manipulate it" mentality. $ selects the Document object, and ready is the way it operates. The process problem is very clear, and the way to the back of the chain is to be executed.
(function(){var isready=False//Determine if the Ondomready method has been executedvar readylist= [];//Put the method that needs to be executed first in this arrayvar timer;//Timer handle ready=function(FN) {If(IsReady) Fn.call (document);ElseReadylist.push (function () {Return Fn.call (This);});ReturnThis; }var ondomready=function(){Forvar i=0;i<readylist.length;i++{readylist[i].apply (document);} readylist =Null; }var bindready =function(EVT) {if (IsReady)Return; isready=True; Ondomready.call (window);If(Document.removeeventlistener) {Document.removeeventlistener ("domcontentloaded", Bindready,False); }ElseIf(document.attachevent) {document.detachevent ("onreadystatechange", Bindready);if (window = =Window.top) {clearinterval (timer); timer =Null; } } };If(Document.addeventlistener) {Document.addeventlistener ("domcontentloaded", Bindready,False); }ElseIf(document.attachevent) {document.attachevent ("onreadystatechange",function() { if (/loaded|complete/). Test (Document.readystate)) Bindready ();}); if (window = = window.top) {timer = SetInterval (function() { try{isready| | Document.documentElement.doScroll (' left '); // under IE can execute doscroll to determine if the DOM is loaded } catch(e) { return;} bindready ();},5);}}) ();
The above code cannot be used with $ (document). Ready, and should be window.ready.
(3) Promise :
The asynchronous programming model in Commonjs also continues the idea that each asynchronous task returns a Promise object that has a then method that allows the callback function to be specified.
So we can write this:
F1 (). Then (F2). then (F3);
We don't need to focus too much on implementation, we don't have to understand asynchrony, we can do asynchronous programming by simply selecting the object through the function and then doing it.
third, the characteristics of the maintenance chain-type development
In jquery, a plug-in tightly modifies the collected elements, and then returns this element for the next use on the chain. This is the beauty of jquery design and one of the reasons why jquery is so popular. In order to guarantee the chain, you must return this. The following code:
(function ($) {$.fn.resize = function (type, value) {return this.each (function () {var $this = $ (this ); if (!type | | type = = ' width ' this.width (value);} if (!type | | type = = ' height ' this.height (value);});};}) (JQuery);
The calling method is as follows:
iv. Summary of jquery plugin writing
The jquery plugin can be used to make full use of the library, abstracting common functions and "recycling". The following is a brief summary:
- Use (function ($) {//plugin}) (JQuery) to wrap your plugin
- Do not repeat the package in the initial range of the plug-in
- Unless you return the original value, the this pointer is returned to guarantee a chain-
- Instead of using a string of parameters, use an object and set the default value
- A plugin, do not attach multiple functions for Jquery.fn
- For your functions, events, data attachment to a namespace
v. References
jquery Plugin Development http://www.cnblogs.com/playerlife/archive/2012/05/11/2495269.html
How jquery chained operations are implemented and why chained operations are http://www.jb51.net/article/33342.htm-
Transferred from: http://www.cnblogs.com/yunfeifei/
jquery plugin writing and chain programming model summary