Organize your notes--jquery

Source: Internet
Author: User
Tags call back

Development steps:

1. Importing jquery files

2. Determine event: Document Load event, initialize page, bind event

3. Implement the function triggered by each event:

1. Gets the element to manipulate, or the value of the response

2. According to these values,. Or the state of the element, to do further operations

< Head > <  type= "Text/javascript"  src= "Jquery.js"></  Script>//jquery references </head>

Document-Ready functions:

Shorthand:

$ (function() {  //  document ready });

The first type:

$ (document). Ready (function//  ...) Code ... });

This is to prevent the document from running JQuery code before it is fully loaded (ready)

If the function is run before the document is fully loaded, the operation may fail

The second type:

$ (document). Load (function() {    //  ... Code ... });

Who executes the ready and load first?

is ready to execute before load executes

Steps for DOM document loading:

To understand why ready is executed first, the load post-execution needs to understand the next steps of DOM document loading:

(1) parsing the HTML structure

(2) Loading external scripts and style sheet files

(3) Parsing and executing script code

(4) Constructing the HTML DOM model//ready

(5) Loading external files such as pictures

(6) Page loading complete//load

Storage structure: jquery exists to get DOM and manipulate DOM! jquery internally uses a form called "Class array Object" as the storage structure

Name conflict:

JQuery uses a method called noconflict () to resolve the problem

var jq=jquery.noconflict ()

Help you use your own name (e.g. JQ) instead of the $ symbol

Note: Some browsers will optimize the code, such as using the child element selector to manipulate the TR result in the table is not possible because the browser automatically added tbody

2. Syntax: $ (selector). Action ()

JQ object to JS object:

$div [0].innerhtml $div. Get (0). InnerHTML  

The Get method can look up the index from behind, plus the minus sign, and the starting index value is-1.

EQ Returns a JQuery object, and get returns a DOM object.

// Error  // correct

Correct wording:

var li = $ ("li"). Get (0 ); $ (LI). css (// packaging with $

The EQ method can only produce a new object, but if you need a collection object, you will use the slice (Start[,end]) method.

JS object to the JQ object:

$ (div). html

jquery objects are not the same as DOM objects.

jquery is a class array object, and the DOM object is a separate DOM element.

If the argument passed to the $ (DOM) function is a DOM object, the jquery method wraps the DOM object into a new jquery object $ (div).

Traversal loop:

$.each (arr,function(i,n)) $ (arr1). Each (function(i,n)); The two ways of looping traversal I represent the index n representing the element object

Anonymous functions:

(function(window, undefined) {    varfunction() {}    ///  ...      = window.$ = jQuery;}) (window);

Summary: The global variable is the devil, the anonymous function can be effectively guaranteed to write JavaScript on the page, without causing the global variable pollution, through the parentheses, let it be loaded immediately initialized, so that a singleton pattern of the effect so that it will only be executed once.

3. Selector: Filter

A. Basic selector:

ID Selector:   #ID名称类选择器:   . Number starts with the class name element selector  :* Selector Group: selector 1, selector 2

B. Hierarchy selector:

> select2 Brothers selector  :+ Select2  (find neighboring brothers) find the next brother find all the younger brothers: Select1~select2 () Find all the younger brothers     

C. Property selector:

element [Property name = ' property value '] [Property name = ' Value of property ']

D. Special selectors:

This, which indicates that the current context object is an HTML object that can invoke properties and methods owned by the HTML object

$ (this), which represents the context object that is a jquery context object that can invoke jquery's methods and property values

E. Basic filter:

: First: Find the number one: even: Even index: odd: Odd index: GT (Index)  : greater than  index greater than: EQ (index)  : Find specified index

F. Form filter:

: Input  finds all entries  including textarea  Select button  input:text  only find type=  Text single line input literal is () judged

4. Events

On () Multi-event binding (all shortcut events are handled at the bottom by an "on" method)

Basic usage:. On (events, [selector], [data])

You can customize the event name

Multiple events bind different functions

$ ("#elem"). On ({    mouseover:function() {},     mouseout:function() {}, });

By separating the spaces, passing different event names, you can bind multiple events at the same time, and each event executes its own callback method.

Remove the binding through the off () method

Event handling

Depending on how you handle the bubbling process:

1. Trigger () Triggerhandler () recommends using this 2.mouseenter () recommendation with this 1. 1 version not found MouseOver ()

Select events can only be used with <input> elements and <textarea> elements

5. Effects

Property:

"Slow" | Default ("normal") | "Fast" or ms Hide () hides show  ()  show  Toggle () two in Fadein () Fade in  fadeOut () Fade Fadetoggle () two in a  Fadeto () Gradually change the selected element to a given opacity

Animation: The underlying is a queue structure (allows a series of functions to be called asynchronously without blocking the program)

Slidedown () swipe down slideup () swipe up Slidetoggle () two in all

6.DOM operation

The attr () Prop () method can be used to set/change property values, and you can set multiple properties at the same time.

Difference:

If you are manipulating an element's original property, with prop (), if you are manipulating a custom property with it attr (), it is recommended to use prop (), unless the custom attribute is attr () in H5.

Get and set

Text ()---Sets or returns the value of a form field

Variance Summary:

where the. html () and. Text () methods cannot be used on form elements, while. val () can only be used on form elements. In addition, when the HTML () method is used on more than one element, only the first element is read, the. Val () method is the same as. html (), and if it is applied on more than one element, only the value of the first FORM element is read, but. Text () is not the same as if. Text () When applied to multiple elements, the text content of all selected elements is read.

Add to:

Append ()- insert content at the end of the selected element (add a child) AppendTo ()----insert the content before the selected element

Delete:

Remove ()---preserves the deletion of data

7. Traversal operation (for DOM)

Concept: means "move", which is used to "find" (or select) HTML elements based on their relationship to other elements. Start with an option and move along this selection until you reach the element you want

Traverse up (ancestor):

the parent () method returns the immediate parent element of the selected element the method traverses the DOM tree only up one level parents () method returns all ancestor elements of the selected element, all the way up to the root element of the document () The Parentsuntil () method returns all ancestor elements between two given elements

Traverse Down (descendants):

The Children () method returns all immediate child elements of the selected element the method traverses the DOM tree only one level down the Find () method returns the descendant elements of the selected element, all the way down to the last descendant

Horizontal Traversal (SIB):

The siblings () method returns all sibling elements of the selected element next () method returns the next sibling element of the selected element Nextall () method returns all following sibling elements of the selected element Nextuntil () The Prev method returns all the following sibling elements between two given arguments (), the Prevall (), and the Prevuntil () methods work in a similar way to the above method, except in the opposite direction: they return the previous sibling element (which is traversed backwards in the DOM tree along the sibling element, Rather than forward)

8.CSS class Operations

Get and set:

AddClass ()---switch operation for adding/removing classes to selected elements CSS () method sets or returns one or more style properties for the selected element

What is the difference between addclass () and CSS ()?

Static with AddClass (), dynamic with CSS ().

9. Data caching

Memory leaks: There is a bug in the browser garbage collection method.

Common memory leaks in several cases:

1. Circular references (but circular references cause memory leaks when there are DOM objects or ActiveX objects in the object that participates in the circular reference).

2.Javascript closures.

3.DOM Insert.

JS memory leaks, no wonder is removed from the DOM element, but there are still variables or objects reference the DOM object. Then the memory can not be deleted, so that the browser memory consumption is high, this memory consumption, as the browser refreshes, will be automatically released.

In another case, a circular reference, a DOM object and the JS object are referenced to each other, so that the situation is more serious, even if the refresh, memory will not be reduced, this is the strict sense of memory leaks.

Caching system: In order to avoid the reference data directly attached to the DOM object, try to avoid the generation of memory leaks

Data cache interface for jquery:

Jquery.data (element, key, value). Data ()

Core: Data is stored in memory and is associated with a direct DOM element through a mapping relationship.

cache[data] = value;

The entire data class is in fact around the Thia.cache internal information to do additions and deletions to check the operation.

Two ways of Caching:

1. DOM element, data is stored in Jquery.cache.

2. Ordinary JS object, the data is stored in the object.

What is the difference between static and instance methods?

1.jquery.data () can be implemented to add a cache for DOM elements or JS objects

2.$ ("Ele"). Data () is an extension of the former, which is designed to easily add cached data to multiple DOM elements via selectors (overwriting the same vaule value)

10. Callback Functions and asynchronous

Deferred interface

Design concept:

A higher level of abstraction around three sets of data:

1. Trigger callback Function List Execution (function name)

2. Add a callback function (name of the function)

3. Callback function list (Jquery.callbacks object)

3.Deferred final status (except for the third set of data)

Callback Method/Event subscription

Done, fail, progress

Notification Method/Event Publishing

Resolve, Reject, notify, Resolvewith, Rejectwith, Notifywith

1. If there is a deferred final state, the default is to pre-add three callback functions to the list in Donelist,faillist

if (statestring) {  list.add(function() {    = statestring;   ^ 1][2].disable, tuples[2][2].lock);}

Tips:

I ^ 1 bitwise XOR operator

So actually the second pass parameter is 1, 0 index swapped, so the value is faillist.disable and donelist.disable

By statestring the value of this condition, advance to the list in the Donelist,faillist to add three callback functions, respectively:

Donelist: [Changestate, Faillist.disable, processlist.lock]faillist: [Changestate, Donelist.disable, Processlist.lock]

Changestate change the state of the anonymous function, deferred state, divided into three kinds: pending (initial state), resolved (resolution state), rejected (Deny state);

Regardless of whether the deferred object is eventually resolve (or reject), it will disable another function list faillist (or donelist) after first changing the state of the object.

The lock Processlist then maintains its state and finally executes the rest of the previous done (or fail) incoming callback function

So the first step is ultimately around this Add method:

done/fail/is List.add, which is callbacks.add, the callback function is stored in the callback object

The second part is very simple, extending 6 methods to the deferred object:

resolve/reject/Notify is Callbacks.firewith, executes the callback function; Resolvewith/rejectwith/notifywith is Callbacks.firewith Queue Method Reference

Finally merge promise to deferred

Promise.promise (deferred); Jquery.extend (obj, promise);

So finally all the methods of the asynchronous object deferred built by the factory method, return the internal deferred object

2.jQuery has taken object save processing:

Core idea: Each time the then operation, as is to create a new deferred object, then each object is enough to save their own state and their own processing methods, through a way to all the object operations are concatenated together

Then structure

Thenfunction(/*Fndone, Fnfail, fnprogress*/ ) {         varFNS =arguments; returnJquery.deferred (function(Newdefer) {Jquery.each (tuples,function(i, tuple) {deferred[tuple[1]] (function() {                         //deferred[Done | fail | progress]                    });         }); }). Promise ()

In fact, a new deferred object is created internally, but the difference here is by passing a callback function, the argument is newdefer, in fact deferred internal is to change the context this is deferred, and then pass deferred to this callback function , so newdefer points to the internal deferred object.

So how do objects relate to each other?

Jquery.each (Tuples,function(i, tuple) {//Remove Parameters  varfn = jquery.isfunction (fns[i]) &&Fns[i]; //deferred[Done | fail | progress] for forwarding actions to Newdefer  //How to add done fail progress  //dealing with the delay object directlydeferred[tuple[1]] (function() {    varreturned = FN && fn.apply ( This, arguments); if(Returned &&jquery.isfunction (returned.promise))    {returned.promise (). Done (Newdefer.resolve). Fail (Newdefer.reject). Progress (newdefer.notify); } Else{newdefer[tuple[0] + "with"] ( This= = = Promise? Newdefer.promise (): ThisFn?[returned]: arguments); }});

Put the then method through:

Deferred.donedeferred.faildeferred.progress

is added to the respective execution queue of the previous object, which enables association calls between different objects.

Process simulation:

1. Pass multiple asynchronous objects, and then traverse each asynchronous object to bind the done, fail, and Progess methods to each object, nothing more than to listen for each asynchronous state (success, failure), if it is done naturally activates the Do method.

2. Updatefunc is a listening method that determines whether all processing or failure processing has been done by judging the number of times an asynchronous object executes.

3. Because when also to form an asynchronous operation, such as when (). Do (), so the inside must create a new jquery.deferred () object, which is used to call back chaining.

4. Listen to all asynchronous objects now (D1,d2 ...) Updatefunc's processing is complete, will give a correct notification to when the done method, because it was created through the third Step jquery.deferred (), so at this point you need to send a message to this above, namely:

Deferred.resolvewith (contexts, values);

5. Internal jquery.deferred () because externally bound when (). Do (), so done naturally received the message Updatefunc, can continue after the operation.

1. Callback Functions (function () {})

Concept:

1. A callback function passed as a parameter to another function is that we simply pass the function definition, we do not execute the function in the argument, we do not pass a function like our usual execution function with a pair of execution parentheses ().

2. The callback function will not be executed immediately, it will be "callback" at a specific point in the function containing it.

Callbacks It is a multipurpose callback function list Object

Callbacks.add (): Adds a collection of callbacks or callbacks to the callback list. Callbacks.disable (): Disables callbacks in the callback list. Callbacks.disabled (): Determines whether the callback list has been disabled. Callbacks.empty (): Removes all callbacks from the list. Callbacks.fire (): Invokes all callbacks with the given parameters. Callbacks.fired (): Accesses all callbacks in the given context and argument list. Callbacks.firewith (): Accesses all callbacks in the given context and argument list. Callbacks.has (): Determines whether a callback is provided in the list. Callbacks.lock (): Locks the list of callbacks for the current state. Callbacks.locked (): Determines whether the callback list is locked. Callbacks.remove (): Removes a callback or callback collection from the callback list. Callbacks.memory: Keep the previous value, add the latest value to the back of this list immediately execute call any callback Callbacks.unique: Make sure you can only add one callback at a time (so there are no duplicate callbacks in the list) Callbacks.stoponfalse: Interrupts call when a callback returns false

2.Deferred Asynchronous model

Deferred provides an abstract, non-blocking solution (such as a response to an asynchronous request) that creates a promise object that returns a response at some point in the future, simply as a processing scheme for an asynchronous/synchronous callback function.

function Task (name) {  var dtd = $. Deferred ();  SetTimeout (function() {    dtd.resolve (name)  +)  return  DTD;} $.when (task one), task (' Task two '). Done (function() {  alert (' success ')})

When (): Merging multiple asynchronous operations

Organize your notes--jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.