Complete jQuery design ideas-jquery-js tutorial

Source: Internet
Author: User
According to statistics, 1 million of the top 46% websites in the world use jQuery, far exceeding other libraries. Microsoft even uses jQuery as their official library.

JQuery is currently the most widely used javascript function library.

According to statistics, 1 million of the top 46% websites in the world use jQuery, far exceeding other libraries. Microsoft even uses jQuery as their official library.

For Web developers, learning jQuery is necessary. It helps you understand the most common technologies in the industry, lay the foundation for learning more advanced libraries in the future, and can easily make many complex effects.

Although jQuery is easy to use and easier to learn than other libraries, it is not easy to fully master it. Because it involves all aspects of web development, there are thousands of methods and internal changes. Beginners often find it easy to get started and difficult to improve.

Currently, jQuery Fundamentals is the best entry material for jQuery on the Internet, written by Rebecca Murphey ). Search for "jQuery training" in Google. This book ranks first. The official jQuery team has agreed to use this book as the basis for official tutorials.

Although this book is an entry-level teaching material, it has more than 100 pages. I made a detailed note on it, trying to clarify jQuery's design ideas and find out the learning context. My goal is to have a full understanding of jQuery. When I encounter problems, I have a thorough understanding of which function is used, and then I can quickly find a specific method from the manual.

The following is my notes. It should be one of the few jQuery Chinese tutorials on the Internet. You only need a little basic knowledge of the javascript language to understand it and grasp all the main aspects of jQuery in the shortest time (except ajax and plug-in development ).

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

JQuery Design Philosophy

Http://jqfundamentals.com/book/

Translated by Ruan Yifeng

[Directory]

1. Select webpage Elements

Ii. Change the result set

Iii. Chain Operations

Iv. Operation of elements: value and value assignment

5. Element operations: Move

Vi. Operations on elements: copying, deleting, and creating

VII. Tools and methods

8. Event operations

9. Special Effects

[Body]

1. Select webpage Elements

The basic design and usage of jQuery is"Select a webpage element and perform some operations on it". This is the fundamental feature that distinguishes it from other function libraries.

The first step of using jQuery is to put a selection expression into the constructor jQuery () (abbreviated as $) and then get the selected element.

The selection expression can be a CSS selector:

$ (Document) // select the entire document object

$ ('# Myid') // select the webpage element whose ID is myId.

$ ('P. myclass') // select the p element whose class is myClass.

$ ('Input [name = first] ') // select the input element whose name attribute is equal to first.

It can also be a jQuery-specific expression:

$ ('A: first ') // select the first a element in the webpage

$ ('Tr: odd') // select an odd row in the table

$ ('# MyForm: input') // select the input element in the form.

$ ('P: visable') // select the visible p element.

$ ('P: gt (2) ') // select all p elements except the first three

$ ('P: animated') // select the p element in the animation state.

Ii. Change the result set

If multiple elements are selected, jQuery provides a filter to narrow down the result set:

$ ('P'). has ('P'); // select the p element that contains the p element

$ ('P'). not ('. myclass'); // select the p element whose class is not equal to myClass.

$ ('P'). filter ('. myclass'); // select the p element whose class is equal to myClass.

$ ('P'). first (); // select 1st p elements

$ ('P'). eq (5); // select 6th p elements

Sometimes, we need to start from the result set and move it to a nearby element. jQuery also provides the moving method on the DOM tree:

$ ('P'). next ('P'); // select the first p element after the p element

$ ('P'). parent (); // select the parent element of the p element.

$ ('P'). closest ('form'); // select the form parent element closest to p.

$ ('P'). children (); // select all child elements of p.

$ ('P'). siblings (); // select the peer element of p.

Iii. Chain Operations

After you select a webpage element, you can perform some operations on it.

JQuery allows all operations to be connected and written in the form of a chain. For example:

('P'hangzhou.find('h3'hangzhou.eq(2).html ('hello ');

It is as follows:

$ ('P') // locate the p element

. Find ('h3 ') // select the h3 Element

. Eq (2) // select 3rd h3 Elements

. Html ('hello'); // change its content to "Hello ".

This is jQuery's most commendable and convenient feature. The principle is that each step of jQuery operations returns a jQuery object, so different operations can be connected together.

JQuery also provides the. end () method, so that the result set can be taken back one step:

$ ('P ')

. Find ('h3 ')

. Eq (2)

. Html ('hello ')

   . End () // return to the step of Selecting All h3 Elements

. Eq (0) // select the first h3 Element

. Html ('World'); // change its content to "World ".

Iv. Operation of elements: value and value assignment

The most common requirement for webpage elements is to obtain their values or assign values to them.

JQuery uses the same function to complete values (getter) and values (setter ). Whether it is a value or a value is determined by the function parameters.

Parameters ('h1').html (); // No parameter in html (), indicating to retrieve the h1 Value

Values ('h1'{.html ('hello'); // html () has the parameter "Hello", indicating that h1 is assigned a value.

Common values and value assignment functions are as follows:

. Html () to retrieve or set html content

. Text () to retrieve or set text content

. Attr () retrieves or sets the value of an attribute.

. Width () to retrieve or set the width of an element

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

. Val () retrieves the value of a form element.

Note that if the result set contains multiple elements, all the elements in the result set are assigned values, only the value of the first element (. with the exception of text (), It extracts the text content of all elements ).

5. Element operations: Move

There are two methods to move the selected element: one is to move the element directly, and the other is to move other elements so that the target element can reach the desired position.

If we select a p element, we need to move it to the end of the p element.

The first method is to use. insertAfter () to move the p element after the p element:

$ ('P'). insertAfter ('P ');

The second method is to use. after () to add the p element to the front of the p element:

$ ('P'). after ('P ');

On the surface, the two methods have the same effect. The only difference seems to be the difference in the operational perspective. But in fact, they have a major difference, that is, they return different elements. The first method returns the p element, and the second method returns the p element. You can select which method to use as needed.

There are four pairs of operations using this mode:

. InsertAfter () and. after (): insert an element from the end of an existing element outside the existing element.

. InsertBefore () and. before (): insert an element from the front of an existing element outside the existing element.

. AppendTo () and. append (): insert an element from the end of an existing element.

. PrependTo () and. prepend (): insert an element from the front inside the existing element

Vi. Operations on elements: copying, deleting, and creating

Use. clone () to copy elements ().

Use. remove () and. detach () to delete elements (). The difference between the two lies in that the former does not retain the event of the deleted element, and the latter retains it, which is useful for re-inserting documents.

Use. empty () to clear the element content (but not delete it ().

The method for creating a new element is very simple. Just pass the new element directly into the jQuery constructor:

$ ('

Hello

');

$ ('

  • New list item
  • ');

    $ ('Ul '). append ('

  • List item
  • ');

    VII. Tools and methods

    In addition to operations on selected elements, jQuery also provides some tool methods (utility) that can be directly used without selecting elements.

    If you understand the inheritance principle of the Javascript language, you can understand the essence of the tool method. It is a method defined on the jQuery constructor, that is, jQuery. method (), so it can be used directly. The methods for operating elements are defined on the prototype object of the constructor, that is, jQuery. prototype. method (). Therefore, instances (I .e. selected elements) must be generated for use. If you don't understand the difference, there is no problem. You just need to understand the tool method as a method that can be directly used just like a javascript native function.

    Common tool methods include:

    $. 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. If the value is not in the array,-1 is returned.

    $. Grep () returns elements that conform to a certain standard in the array.

    $. Extend () combines multiple objects into the first object.

    $. MakeArray () converts an object to an array.

    $. Type () determines the object category (function object, date object, array object, regular object, and so on ).

    $. IsArray () determines whether a parameter is an array.

    $. IsEmptyObject () determines whether an object is null (excluding any attributes ).

    $. IsFunction () determines whether a parameter is a function.

    $. IsPlainObject () determines whether a parameter is an Object created with "{}" or "new Object.

    $. Support () determines whether the browser supports a certain feature.

    8. Event operations

    JQuery can bind events to webpage elements. Run corresponding functions based on different events.

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

    Alert ('hello ');

    });

    Currently, jQuery mainly supports the following events:

    The. blur () form Element loses focus.

    The value of the. change () form element changes.

    . Click ()

    . Dblclick () double-click the mouse

    . Focus () form elements get focus

    . Focusin () subelement obtains focus

    . Focusout () child element loses focus

    . Hover () specifies the processing function for both the mouseenter and mouseleave events.

    . Keydown () press the keyboard (for a long time, only one event is returned)

    . Keypress () press the keyboard (a long time key will return multiple events)

    . Keyup () loosen the keyboard

    . Load () element loaded

    . Mousedown () press the mouse

    . Mouseenter () move the mouse into (entering the child element is not triggered)

    . Mouseleave () move the mouse away (leaving the child element is not triggered)

    . Mousemove () move the mouse inside the element

    . Mouseout () move the mouse away (also triggered when the child element is left)

    . Mouseover () the mouse enters (it is also triggered when the sub-element is entered)

    . Mouseup () release the mouse

    . Ready () DOM loaded

    . Resize () changes the browser window size

    The position of the. scroll () scroll bar changes.

    . Select () content in the text box selected by the user

    . Submit () User submission form

    . Toggle () runs multiple functions in sequence based on the number of mouse clicks

    . Unload () The user leaves the page

    These events are within jQuery, and they are convenient. bind. You can use. bind () to control events more flexibly. For example, you can bind the same function to multiple events:

    $ ('Input'). bind (

    'Click change', // bind both the click and change events.

    Function (){

    Alert ('hello ');

    }

    );

    Sometimes, you only want to run the event once. You can use the. one () method.

    $ ("P"). one ("click", function (){

    Alert ("Hello"); // runs only once, and will not run after clicking

    });

    . Unbind () is used to unbind events.

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

    All event processing functions can take an event object as a parameter, such as e in the following example:

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

    Alert (e. type); // "click"

    });

    This event object has some useful attributes and methods:

    The horizontal distance between the mouse and the upper left corner of the webpage when the event. pageX event occurs

    When an event. pageY event occurs, the vertical distance between the mouse and the upper-left corner of the webpage

    Event. type event type (such as click)

    Event. which key is pressed by which?

    Event. data is bound to the event object and then passed into the event processing function.

    Webpage elements targeted by the event.tar get event

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

    Event. stopPropagation () Stop the event and bubble up the Layer Element

    In the event processing function, you can use the this keyword to return the DOM elements for the event:

    $ ('A'). click (function (){

    If ($ (this). attr ('href '). match ('evil') {// if it is identified as a harmful link

    E. preventDefault (); // block open

    $ (This). addClass ('evil '); // Add harmful class

    }

    });

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

    $ ('A'). click ();

    $ ('A'). trigger ('click ');

    9. Special Effects

    JQuery allows objects to present certain special effects.

    $('H1 '). show (); // displays an h1 title

    Common special effects are as follows:

    . FadeIn () fade in

    . FadeOut () fade out

    . FadeTo () Adjust transparency

    . Hide () hidden element

    . Show () display element

    . SlideDown () Expand down

    . SlideUp () Roll Up

    . SlideToggle () expands or rolls up an element in sequence.

    . Toggle () displays or hides an element in sequence.

    Except for. show () and. hide (), the default execution time of all other effects is 400 ms (ms), but you can change this setting.

    $('H1 '). fadeIn (300); // fade in within 300 milliseconds

    $('H1 '). fadeOut ('low'); // fade out slowly

    After the special effect ends, you can specify to execute a function.

    $ ('P'). fadeOut (300, function () {$ (this). remove ();});

    You can use. animate () to customize more complex effects.

    $ ('P'). animate (

    {

    Left: "+ = 50", // shift right continuously

    Opacity: 0.25 // specify the transparency

    },

    300, // duration

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

    );

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

    $. Fx. off if set to true, disable all webpage effects.

    (End)

    Related Article

    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.