Traditional Culture Encyclopedia - Almanac inquiry - How does jquery encapsulate plug-ins? jquery encapsulates plug-ins.

How does jquery encapsulate plug-ins? jquery encapsulates plug-ins.

How to package jquery plug-ins

Foreword Today, jquery is almost an essential tool for web development. Even vs Artifact began to build Jquery and ui into web projects on 20 10. As for the benefits of using jquery, I won't go into details here. I know all the used ones. Today, we will discuss the plug-in mechanism of jquery, which has thousands of third-party plug-ins. Sometimes we write an independent function. If we want to combine it with jquery, we can call it with jquery chain. It is necessary to extend jquery and write it as a plug-in. For example, the following is a simple demonstration of extending the jquery object:

//sample: a method to extend the jquery object. Bold () is used to thicken fonts.

(Function ($) {

$。 fn。 extend({ bold summary/summary

Return to this. CSS({ font weight:bold

}

});

})(jQuery);

Call method:

This is a very simple extension. Next, let's analyze the above code step by step.

First of all, the plug-in mechanism of jquery

In order to facilitate users to create plug-ins, jquery provides jQuery.extend () and jQuery.fn.extend () methods.

The 1.jQuery.extend () method has an overload.

JQuery. extend(object) is used to extend the parameters of the JQuery class itself, that is to say, add a new function or call a static method between the JQuery class and the named null. For example, the ajax methods built into jQuery are all called with jQuery.ajax (), which is a bit like the static method of "class name". Method name ". Let's write an example of jquery. extend(object):

//Extend jQuery.extend ({"minvalue: function (a, b)) of the jquery object itself {/b)){//summary/summary).

return

}, summary/abstract

return

}

}); //Call

vari = 100j = 10 1 varmin _ v = $。 minValue(I,j); //min_v is equal to 100.

varmax_v=$。 max value(I,j); //max_v is equal to 10 1.

Overloaded: jquery.extend ([deep], target, object 1, [objectn])

Extends an object with one or more other objects and returns the extended object.

If target is not specified, jQuery will be named empty to extend itself. This helps plug-in authors add new methods to jQuery.

If the first parameter is set to true, jQuery returns a deep copy, recursively copying any object it finds. Otherwise, the copy will share the structure with the original object.

Undefined attributes will not be copied, but attributes inherited from the object prototype will be copied.

parameter

Depth: Optional. If set to true, recursively merge.

Target: the object to be modified.

1: the object to be merged into the first object.

ObjectN: optional. The object to be merged into the first object.

Example 1:

Merge settings and options, modify and return settings.

Var setting ={validate:false, limit:5, name:foo.

Varoptions={validate:true,name: bar。

JQuery.extend (setting, option);

Results:

Setting = = {Verification: True, Limit: 5, Name:

vardefaults={validate:false,limit:5,name:foo

Varoptions={validate:true,name: bar。

var settings = jquery . extend(empty,default,option);

Results:

Setting = = {Verification: True, Limit: 5, Name: Column.

};

It turns out that jQuery.fn=jQuery.prototype is the prototype of jQuery object. Then the jQuery.fn.extend () method is the prototype method to extend the jQuery object. We know that extending the method on the prototype is equivalent to adding a "member method" to the object, and the "member method" of the class can only be called by the object of the class, so using the method of jQuery. fn. extend(object) extension, the instance of jQuery class can use this "member function". You must distinguish between jquery. fn. extend(object) and jquery. extend(object) methods.

Two. Automatic execution of anonymous functions/closures

1. What is a self-executing anonymous function?

Refers to such a function: (function {//code })();) ();

2.Ask why (function {//code}) (); Can be executed, function {//code }(); (); Will you report an error?

analyse

(1). First, make clear the difference between them: (function{//code}) is an expression, and function{//code} is a function declaration.

(2). Followed by js, because function(){//code} has been explained in the "compile" stage, js will skip function(){//code} and try to execute (); So it will report an error;

When js executes to (function{//code}) (); When, because (function{//code}) is an expression, js will solve it to get the return value. Because the return value is a function, so I met (); When, it will be executed.

In addition, the method of converting a function into an expression does not necessarily depend on the grouping operator (). We can also use void operator, ~ operator,! operator ...

For example:

The writing method of plug-ins in bootstrap framework;

! Function ($) {

//Do something;

}(jQuery);

and

(Function ($) {

//Do something;

})(jQuery); This is one thing.

The biggest use of anonymous function is to create closures (which is one of the characteristics of JavaScript language), and it can also build namespaces to reduce the use of global variables.

For example:

vara = 1;

(Function () () {

vara= 100

})();

Alert (1); //popup 1

For more closures and anonymous functions, see the article anonymous functions and self-execution of Javascript.

Third, package JQuery plug-ins step by step.

Next, let's write a highlighted jqury plug-in.

1. Set a closed area to prevent the plug-in from being "polluted"

//The closure is defined in the named empty(function($))

})(window . jquery);

2. jQuery. fn. extend(object) extends the jQuery method and makes plug-ins.

//The closure is defined in the named empty(function($))

$。 fn。 Extend({ highlight

})(window . jquery);

3. Give the default parameters of the plug-in to realize the plug-in function.

//The closure is defined in the named empty(function($))

$。 fn。 Extend({ Highlight// Use jQuery.extend to override the default parameters of the plug-in.

This. each(function(){// This is a jQuery object.

//When calling the highlight () plug-in collection, traverse all dom to be highlighted.

var $ this = $(this); //Get the jQuery object of the current dom, here is the dom of the current loop.

//Set the style of dom according to parameters.

$ this . CSS ({

Background color:

Color: opts. prospect

});

});

}

}); //Default parameters

vardefaluts={

Foreground: red,

Background: yellow

};

})(window . jquery);

At this point, the basic functions of the highlight plug-in are available. The calling code is as follows:

$(function(){

$(p// Call custom highlighting plug-in});

It can only be called directly here, not in chain. We know that jQuery can be called in a chain, that is, multiple methods can be called on a jQuery object, such as:

$(# id 100 pixels })。 AddAttr (title

But the plug-ins above us can't be chained like this. For example: $(p 100 pixel); //I will report that I can't find the css method because my custom plug-in didn't return the jQuery object after completing the function. Next, return the jQuery object, so that our plug-in also supports chain calls. (In fact, it is very simple, that is, when we finish executing our plug-in code, we return the jQuery object, which is no different from the above code. )

How does jquery get the contents of inputfile?

The method for jquery to get the contents in inputfile:; $(“# conter“)。 val(); //So you can get its value (i.e. content).

1.jQuery is a fast and concise JavaScript framework and an excellent JavaScript code base after Prototype. The purpose of jQuery design is "writeLess, DoMore", which advocates writing less code and doing more. It encapsulates the common function codes of JavaScript, provides a simple JavaScript design pattern, and optimizes HTML document operation, event handling, animation design and Ajax interaction.

2.2. The core features of jQuery can be summarized as follows: unique chain grammar and short and clear multifunctional interface; It has an efficient and flexible css selector and can be extended. It has convenient plug-in extension mechanism and rich plug-ins.

How to use plug-ins?

1. Load the jquery framework with script tags. 2. Load the plug-in with the script tag. 3. See if the plug-in has an api and call it according to the api. 4. If there is no api, read the source code yourself. Generally speaking, the calling method of jquery plug-ins is $ ('element'). PlugName (parameter); Where element is the object you choose to execute the plug-in method, plugName is the name of the method in your plug-in, and param is the parameter of the plug-in method. Of course, some plug-ins are not called this way, and some plug-ins require you to add the following classes to the html tag. This still depends on the api of the plug-in you are using.

Explain in detail how to correctly reference jquery and jquery-ui plug-ins in vue projects.

Vue-cliwebpack introduced jquery on a global scale.

1, first add it in package.json,

Then nmpinstall

2. Add in webpack.base.conf.js

3. Add to the end of module.exports

Plug-in:

4. Then make sure to run dev again.

5. Just introduce it at main.js

Introduce third-party non-NPM modules. Vue file

Vue-cli introduces external files.

Add an external file to webpack.base.conf.js

Swiper in externals is the key, and the corresponding value must be the variable Swiper defined by the plug-in swiper.js:

Then import the file into the index.html file in the root directory: script src = "static/lib/wiper.js"/script >

In this way, you can add this line of code: importSwiperfrom‘swiper‘' to the file that needs to use swiper.js so that it can be used normally.

What are the plug-ins for the home page?

Tool category

A tool library for manipulating objects, arrays, etc.

Underline. js

Lo-dash and underline. The api of js is basically the same. Compared with underline, JS has the advantage of high efficiency. Customized structure

Sugar added some tools and methods for native objects.

Functional.js has got enough support from the library.

Watch.js monitors changes in objects or properties.

Bacon.js functional programming, cool

Streamjs performs a series of operations on arrays and objects through streams.

Asynchronous process control

Eventproxy made by Park Ling

Arbiter.js details

Publish subscription

QPromise type

Asynchronous. js

mimical

Mock.js generates random data and mockAjax requests.

Jquery-mockjaxmockajax request

time base

moment

date

Browser detection

Bowser detects specific browsers and versions.

Ua-parser-js detects specific browsers and versions, operating systems, device types, etc.

Commissioning test/debugging

Console-polyfill can safely use console methods such as console.log ().

Logs make the logs output by the console have style.

Konsole.js outputs log information details in an element of the page.

Uri.jsuri operation

Cookie tool library for adding, deleting and changing cookies.

Controller Front-end Routing Library Details

Digital operation of BigDecimal.js to improve accuracy

JSDoc generates API document details according to the information annotated in javascript files.

Encapsulation of hotkey keyboard events

MD5 encrypts the file library through MD5.

Browser enhancement class

Libraries that make some old browsers great.

Selectivizr makes IE6-8 some css3 selectors.

IeBetter endows ie6-8 with advanced browser features.

ExplorerCanvas enables IE8 browser to support canvas.

CSS3Pie enables IE6-9 to support border-radial, box-shadow and linear-gradient. You can use it. Htc file (note Minetype) or. Js file. When using Pie.js, if the elements of box-radious have a background color, the background color is not displayed. . .

FormFive allows old browsers to support some functions of HTML5 forms, such as placeholders and autofocus.

/anselmh/object-fit enables the browser to support css rules for object adaptation.

HTML5CrossBrowserPolyfills, a bunch of Polyfills.

Flexbox is supported by the flexibility of the old IE.

Selector enhancement

Lining.js allows browsers to achieve effects like:: nth-line (),:: nth-last-line ().

unclassified

Prefixfree uses it, so you don't need to add a browser prefix when writing css.

Form grade

Jquery-file- Upload file component details

ZTree file tree view control

Tree editor. The feeling of sensory display is very similar to mind mapping.

Some processing of files in file selection box by FileAPI

Form validation

. Verification details

JQuery verification engine

Morphological element beautification

Uniform provides beautification of form elements such as drop-down boxes, menus, check boxes and buttons.

Select 2 multi-choice drop-down boxes.

Selectivity and uncertainty are similar.

DropKick drop-down box, single choice and multiple choice. Appearance is better than uniform.

Switch ios7 switch assembly

Nouislider uses the scroll bar to set/control (volume, etc. ).

Range.css beautifies the appearance of the input element.

Picture class

Holderjs generates placeholder pictures.

lazybones

Image loading performs a recall after all selected images are loaded.

CSSgram implements the Instagram filter library with the filters of CSS3.

Icon category

Icon font summary

Icons made by SVG

svgicons

Iconic

HYBICON with interactive effect. Such as hovering, clicking

HTML character entity icon

/

When you click the transformicons icon, there will be some deformation effects. For example, the plus sign becomes a cross.

Tilable textures generated by css3patternscss3. Browser compatibility is not good.

Browse pictures

Fancybox pops up to view pictures, videos and other demonstrations.

Yoxview pops up to view the picture, and the picture size scales naturally.

Picture wall

Wookmark

User interface framework

WeUI is designed by the official design team of WeChat for the development of WeChat Web.

Frame 7

UI component class

drag

Dragula supports dragging, dropping and sorting. It feels lighter and easier to use than jqueryUI.

Angular-official angular version of -dragula dragula

Data visualization (chart)

Echarts produced by Baidu.

Highcharts is very powerful. This is a charge.

Drawable. JS chart library based on D3.

Flot document is not powerful.

ChartJs's Chinese document demonstration is beautiful and clear. Relatively lightweight.

A man in ichartJs China did it, and it felt good.

Time selection component

Foundation-Date Selector

A detailed simple calendar

Fullcalendar supports publishing to change the time of to-do items.

SimpleEventsCalendar looks like it. Charge 5 dollars

JQueryuidatepicker is very classic, not very nice.

Pickadate is light, mobile phone friendly and beautiful. But it seems that it can only be displayed in the popup layer, and there is no drop-down display.

Zebra-datepicker is very configurable. But it seems that it can only pop up in the upper right. . .

Bootstrap- date selector bootstrap style

DateRangePicker select a time period. Bootstrap style This component relies on TwitterBootstrap, Moment.js and jQuery.

Custom scroll bar

Perfect scroll bar lightweight scroll bar. Looks like a scroll bar for chrome on a mac.

Iscroll works well on mobile devices.

Load effect

CSSSpinnersCSS did it.

Loaders.cssCSS made it.

Table component

jsGridDataGrid。 detailed

Data grid based on Backgrid

Excellentexport generates the table contents into Excel. Compatible with Firefox, Chrome and IE6+

Data tables are interactive (sorting, deleting, etc.). )

Handsontable generates data in the appearance of Excel.

Component library of JSpreadsheets table data

Get color

range

Share to social networks

This will generate shared code.

edit

Ace code editor can be used for demo demonstration.

bookmaker

Ueditor Baidu made it.

Tinymce edits html content in real time.

Summernote works well on mobile devices.

Notification component

notie.js

HTML5 player

Jwplayer is used by a large number of websites.

Html 5 media simple H5 player, lightweight

Jplayer is powerful and can change skin.

show

Impress.js all kinds of rotation, strange experience.

Full screen display. Use the scroll wheel to turn pages in detail.

Zepto.fullpage focuses on fullPage.js on the mobile side and relies on Zepto.

Page stacking is similar to a full page.

Turn.js makes a book with beautiful page turning effect.

Slide show

Slidesjs is quite easy to use, but you have to write CSS for slide navigation yourself, hehe in detail.

There are no details of the ISlider javascript sliding component of the mobile phone platform that the plug-in depends on.

Bgstretcher full-screen slides will change with the change of page size.

Swiper is an open source, free and powerful mobile touch sliding plug-in Swiper Chinese website.

Coin slider is compatible with IE6. Pretty good ~. However, the switching mode is block by block. Unable to configure switching mode. . .

When switching, Wowslider slides will show all kinds of cool effects. Charge.

Cycle2 normal slides do not support vertical scrolling. . .

Jcarousel ordinary slide, which is not compatible with IE6.

Displays three-dimensional scrolling. It's good to do ppt

Nodeppt is made by China people, and ppt is also quite good. Some aspects are better than reveal's. However, there are some problems in generating exported html.

Roundabout3d switch, look at the edge of the picture behind.

Pop-up box

Magnific-Popup is compatible with PC and mobile devices. Not bad, there are 5k+ stars.

The layer developed by China people is compatible with ie6+. I don't like its name.

Animation effect

Mixitup uses beautiful animation effects to complete sorting and filtering.

Checkbox Checkbox Effect

Flip effect of quick flip card

Flop effect 2 compatibility can be. The writing method is relatively simple: 1, which only supports flipping 2 in X direction, and the class name is specified as 3, which can only be called once. It needs to rewrite my improved version here.

The theater simulates two people talking on the screen.

The color of midnight.js text changes with the background, and _ explodes.

The animation of jquery, the color gradient animation plug-in of Color-animationjquery, does not support the change of color value. Change libraries can provide this support.

Transit converts elements into css.

Tagcanvas3D tag cloud effect is detailed.

Iconate screen switching animation

The appearance effect of Snap.js left/right navigation

CSSshake jitter animation

Some cool effects after clicking ClickSpark.js

Visual difference plug-in

Scrollorama is relatively simple.

Superscrollorama can do more, but it needs to use a third-party tween library, using