jquery design ideas and programming ideas, J Elegant JS Library Internal Secrets __ Small Program

Source: Internet
Author: User

jquery is currently the most widely used JavaScript library of functions.

According to statistics, the world's top 1 million websites, 46% use jquery, far more than other libraries. Microsoft even took jquery as their official repository.

It is necessary for web developers to learn jquery. Because it gives you an idea of the industry's most versatile technology, lays the groundwork for a more advanced library in the future, and it does make a lot of complex effects easy.

Although jquery is easy to start with, it's easier to learn than other libraries, but it's not easy to master. Because it involves all aspects of web development, there are thousands of methods and internal changes available. Beginners often feel that getting started is very convenient and difficult to improve.

At present, the best jquery primer on the internet is the jquery Basics (jquery Fundamentals) written by Rebecca Murphey. Search for "JQuery training" in Google, the book is ranked first. The jquery official team has agreed to use the book as the basis for an official tutorial.

===========================================

jquery Design Idea

Directory

First, select the page elements

Ii. change of result set

Third, the chain of operation

Iv. operation of elements: values and Assignments

V. Operation of elements: moving

Vi. operations of elements: copying, deleting, and creating

Vii. Tools and methods

Eight, the event operation

IX. Special Effects

Body

First, select the page elements

The basic design idea and main usage of jquery is "select a page element and then do some action on it." This is the fundamental feature that distinguishes it from other JavaScript libraries.

The first step in using jquery is often to put a select expression into the constructor jquery () (abbreviated $) and get the selected element.

Select an expression can be a CSS selector:

$ (document)//Select entire Document Object

$ (' #myId ')//select page element with ID myId

$ (' div.myclass ')//select div element with class as MyClass

$ (' input[name=first] ')//select the INPUT element with the Name property equal to the

Or it can be a jquery-specific expression:

$ (' A:first ')//Select the first a element in the page

$ (' tr:odd ')//select odd row of table

$ (' #myForm: Input ')//Select INPUT element in the form

$ (' div:visible ')//select visible div element

$ (' Div:gt (2) ')//Select all DIV elements except the first three

$ (' div:animated ')//Select the currently animated DIV element

Ii. change of result set

The second of the jquery design idea is to provide a variety of powerful filters, filter the result set, and narrow the selection results.

$ (' div '). has (' P '); Select the div element that contains the P element

$ (' div '). Not ('. MyClass '); Select a DIV element with class not equal to MyClass

$ (' div '). Filter ('. MyClass '); Select the div element with class equal to MyClass

$ (' div '). Select a 1th div element

$ (' div '). EQ (5); Select a 6th div element

Sometimes we need to move from a result set to a nearby related element, and jquery also provides a way to move through the DOM tree:

$ (' div '). Next (' P '); Select the first P element after the DIV element

$ (' div '). parent (); Select the parent element of a DIV element

$ (' div '). Closest (' form '); Select the form parent element closest to the Div

$ (' div '). Children (); Select all child elements of a div

$ (' div '). siblings (); Select the sibling element of a Div

Third, the chain of operation

The third of the jquery design idea is that after the page element is finally selected, a series of operations can be performed on it, and all operations can be connected together and written in the form of a chain, such as:

$ (' div '). Find (' H3 '). EQ (2). html (' Hello ');

Break it down, it's like this:

$ (' div ')//Find DIV element

. Find (' H3 ')//Select the H3 element

. EQ (2)//Select the 3rd h3 element

. html (' Hello '); Change its contents to Hello

This is the most admirable and convenient feature of jquery. It is the principle of each step of the jquery operation, the return is a jquery object, so different operations can be linked together.

jquery also provides an. End () method that allows the result set to step back:

$ (' div ')

. Find (' H3 ')

. EQ (2)

. html (' Hello ')

. End ()//back to the step where all the H3 elements are selected

. EQ (0)//Select the first H3 element

. HTML (' World '); Change its content to world

Iv. operation of elements: values and Assignments

The most common requirement for manipulating page elements is to get their values, or to assign them.

The four of the jquery design idea is to use the same function to complete the values (getter) and assignment (setter), that is, the "accessor" and "the assignment" in unity. Whether it is a value or an assignment is determined by the parameters of the function.

$ (' H1 '). html (); HTML () does not have a parameter to indicate the value of fetching H1

$ (' H1 '). html (' Hello '); The HTML () has the parameter hello, representing the assignment to the H1

Common values and assignment functions are as follows:

. HTML () Fetching or setting HTML content

. text () Remove or set text content

. attr () to remove or set the value of a property

. width () to remove or set the width of an element

. Height () to remove or set the height of an element

. val () Remove the value of a FORM element

It is important to note that if the result set contains more than one element, the value is assigned to all of them, and when the value is fetched, only the value of the first element (. Text (), which takes out the text content of all the elements).

V. Operation of elements: moving

The five idea of jquery design is to provide two sets of methods to manipulate the position of elements in a Web page. One group of methods is to move the element directly, and the other is to move the other elements so that the target element reaches the position we want.

Assuming we have a DIV element selected, we need to move it back to the P element.

The first method is to use. InsertAfter (), which moves the DIV element after the P element:

$ (' div '). InsertAfter ($ (' P '));

The second method is to use. After () to add the P element to the DIV element:

$ (' P '). After ($ (' div '));

On the surface, the effects of the two methods are the same, and the only difference seems to be a different view of the operation. But in fact, they have a significant difference, that is, the returned elements are not the same. The first method returns the DIV element, and the second method returns the P element. You can choose which method to use according to your needs.

There are four pairs of operations using this pattern:

. InsertAfter () and. After (): Inserts an element from the outside of an existing element

. InsertBefore () and. Before (): Inserts an element from the front, outside the existing element

. Appendto () and. Append (): Inside an existing element, inserting elements from behind

. Prependto () and. Prepend (): Inside an existing element, insert an element from the front

Vi. operations of elements: copying, deleting, and creating

In addition to the location movement of elements, JQuery provides important methods for several other operational elements.

The copy element uses. Clone ().

Delete elements use. Remove () and. Detach (). The difference is that the former does not retain the event of the deleted element, which is reserved for use when the document is reinserted.

Empties the element content (but does not delete the element) using. Empty ().

The way to create new elements is simple, just pass the new elements directly into the jquery constructor:

$ (' <p>Hello</p> ');

$ (' <li class= "new" >new list item</li> ');

$ (' ul '). Append (' <li>list item</li> ');

Vii. Tools and methods

Six of jquery design ideas: In addition to manipulating selected elements, there are some tool methods (utility) that are not related to elements. You can use these methods directly without having to select the elements.

If you understand the principles of JavaScript language inheritance, you can understand the essence of the tool approach. It is the method defined on the jquery constructor, that is, Jquery.method (), so it can be used directly. And those that manipulate the elements are the methods that define the prototype object on the constructor, that is, JQuery.prototype.method (), so you must generate the instance (that is, the selected element) to use. If you do not understand this distinction, the problem is not the case, as long as the tool method is understood as a JavaScript native function, you can use the method directly.

Common tool methods are as follows:

$.trim () removes spaces at both ends of the string.

$.each () traverses an array or object.

$.inarray () returns the index position of a value in the array. Returns-1 if the value is not in the array.

$.grep () returns elements in an array that conform to a certain standard.

$.extend () merges multiple objects into the first object.

$.makearray () Converts an object to an array.

$.type () determines the class of objects (Function objects, date objects, array objects, regular objects, and so on).

$.isarray () Determines whether an argument is an array.

$.isemptyobject () Determines whether an object is empty (does not contain any attributes).

$.isfunction () Determines whether a parameter is a function.

$.isplainobject () Determines whether an argument is an object established with "{}" or "New object".

$.support () determines whether the browser supports an attribute.

Eight, the event operation

The idea of the jquery design is to bind events directly above the page elements.

$ (' P '). Click (function () {

Alert (' Hello ');

});

Currently, jquery mainly supports the following events:

. blur () The form element loses focus.

. Change () The value of the form element has changed

. Click () mouse clicks

. DblClick () mouse double-click

. focus () The form element gets focused

. Focusin () child element gets focus

. Focusout () child element loses focus

. Hover () Specify the handler function for both the MouseEnter and MouseLeave events

. KeyDown () Press the keyboard (long time key, return only one event)

. KeyPress () Press the keyboard (long time key, will return multiple events)

. KeyUp () Release the keyboard

. Load () element loading complete

. MouseDown () Press the mouse

. MouseEnter () mouse entry (Enter child element does not trigger)

. MouseLeave () mouse left (left child element does not trigger)

. MouseMove () mouse moves inside an element

. Mouseout () mouse left (also triggered by leaving child elements)

. mouseover () mouse enter (also trigger when entering child element)

. MouseUp () Release mouse

. Ready () Dom load complete

. Resize () the size of the browser window has changed

. Scroll () The position of the scroll bar has changed

The. Select () user selects the contents of the text box

. Submit () The user submits the form

. Toggle () Run multiple functions sequentially based on the number of mouse clicks

. Unload () User leaves page

These events, within jquery, are a convenient way of. Bind (). Use. Bind () to control events more flexibly, such as binding the same function for multiple events:

$ (' input '). Bind (

' Click Change ',//Bind the Click and change events at the same time

function () {

Alert (' Hello ');

}

);

Sometimes you just want the event to run once, when you can use the. One () method.

$ ("P"). One ("click", Function () {

Alert ("Hello"); Run only once and future clicks will not run

});

. Unbind () is used to disassociate event bindings.

$ (' P '). Unbind (' click ');

All event-handling functions can accept an event object as an argument, such as E in the following example:

$ ("P"). Click (function (e) {

alert (E.type); "Click"

});

This event object has some useful properties and methods:

The horizontal distance of the mouse from the upper-left corner of the page when the Event.pagex event occurs

The vertical distance of the mouse from the upper-left corner of the page when the Event.pagey event occurs

Type of Event.type event (for example, click)

Which key did Event.which press?

Event.data bind data to the event object, and then pass in the event handler function

Event.target Event-oriented page element

Event.preventdefault () blocks the default behavior of an event (for example, clicking a link will automatically open a new page)

Event.stoppropagation () Stop event bubbling to upper element

In the event handler function, you can use the This keyword to return the DOM element for the event:

$ (' a '). Click (function (e) {

if ($ (this). attr (' href '). Match (' evil ') {//if identified as a harmful link

E.preventdefault (); Block Open

$ (this). addclass (' evil '); Add a bad class

}

});

There are two ways to automatically trigger an event. One is to use the event function directly, and the other is to use the. trigger () or. Triggerhandler ().

$ (' a '). Click ();

$ (' a '). Trigger (' click ');

IX. Special Effects

Finally, jquery allows objects to render certain special effects.

$ (' H1 '). Show (); Show a H1 title

The special effects commonly used are as follows:

. FadeIn () Fade in

. fadeout () Fade out

. Fadeto () Adjust transparency

. Hide () hidden elements

. Show () display elements

. Slidedown () expand Down

. Slideup () Roll up

. Slidetoggle () Expand or roll up an element in turn

. Toggle () To show or hide an element in turn

Except for. Show () and. Hide (), the default execution time for all other effects is 400ms (milliseconds), but you can change this setting.

$ (' H1 '). FadeIn (300); Fade in in 300 milliseconds

$ (' H1 '). fadeout (' slow '); Slowly fade out

After the effect is complete, you can specify that a function be executed.

$ (' P '). fadeout (+, function () {$ (this). Remove ();});

More complex effects, you can use. Animate () customization.

$ (' div '). Animate (

{

Left: "+=50",//Moving right

opacity:0.25//Specify Transparency

},

300,//Duration

function () {alert (' done! ');}//Callback function

);

. Stop () and. Delay () are used to stop or delay the execution of effects.

$.fx.off if set to True, all web effects are turned off.

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.