Jquery learning Summary (super detailed) _ jquery

Source: Internet
Author: User
Tags jquery cdn
This article only summarizes some of jquery's knowledge points. more comprehensively, you can go to the official website to view Chinese documents. You can learn more about jquery and its features.
Window. onload $ (Document). ready ()
Execution time You must wait until all the content on the webpage is loaded (including images ). All DOM structures in the web page are executed after being drawn. It is possible that the related content of DOM elements has not been fully loaded.
Write count You cannot write multiple codes at the same time. The following Code cannot be correctly executed: window. onload = function ({alert ("test1");} window. onload = function () {alert ("test2");} The result will only output "test2" You can write multiple
Simplified writing None $ (Document). ready (function () {}); can be abbreviated to $ (function (){});
 

1. Select webpage Elements

The basic design and usage of jQuery is to "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 containing 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:

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

2. find ('h3 ') // select the h3 Element

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

4. 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:

1. $ ('P ')
2. find ('h3 ')
3. eq (2)
4. html ('hello ')
5. end () // return to the step of Selecting All h3 Elements
6. eq (0) // select the first h3 Element
7. html ('World'); // change its content to "World ".
. End (): Return to the latest "destructive" operation. If no destructive operation is performed before, an empty set is returned. The so-called "destructive" refers to the operation of any change to the matching jQuery element.

Example
Description: Selects all p elements, finds and selects span sub-elements, and then returns to select p elements.

HTML code:

Hello, how are you?

JQuery code: $ ("p"). find ("span"). end () Result:

Hello how are you?

-4. 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:

1. html () returns or sets the content of the selected element (inner HTML)
2. extract or set text content in text ()
3. attr () retrieves or sets the value of an attribute.
4. width () is used to retrieve or set the width of an element.
5. height () is used to retrieve or set the height of an element.
6. val () is used to retrieve or set the html content to retrieve 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
. InsertAfter (), move the p element behind the p element:

$ ('P'). insertAfter ('P ');
. After (), add the p element to the front of the p element:
 

$ ('P'). after ('P ');
There are a total of four

1. insertAfter () and. after (): insert an element from the end of an existing element outside the existing element.
2. insertBefore () and. before (): insert the element from the front outside of the existing element
3. appendTo () and. append (): insert an element from the end of an existing element.
4. prependTo () and. prepend (): insert the element from the front inside the existing element


1. after ():
Description:
Insert a jQuery object (similar to a DOM element array) After all paragraphs ).

HTML code:Hello

I wowould like to say:

JQuery code: $ ("p"). after ($ ("B"); Result:

I wowould like to say:

Hello

2. insertAfter ():
Description:
Insert all paragraphs into one element. Same as $ ("# foo"). after ("p ")

HTML code:

I wowould like to say:

Hello

JQuery code: $ ("p"). insertAfter ("# foo"); Result:

Hello

I wowould like to say:

3. before ():
Description:
Insert a jQuery object (similar to a DOM element array) before all paragraphs ).

HTML code:

I wowould like to say:

HelloJQuery code: $ ("p"). before ($ ("B"); Result:Hello

I wowould like to say:


4. append ():
Description: adds HTML tags to all paragraphs.

HTML code:

I wowould like to say:

JQuery code: $ ("p"). append ("Hello"); Result:

I wowould like to say:Hello


5. appendTo ()
Description: adds a new paragraph to p and adds a class.

HTML code:

JQuery code: $ ("

"). AppendTo (" p "). addClass (" test "). end (). addClass (" test2 "); Result:


6. prepend ()
Description: A jQuery object (similar to a DOM element array) is prefixed to all paragraphs ).

HTML code:

I wowould like to say:

HelloJQuery code: $ ("p"). prepend ($ ("B"); Result:

HelloI wowould like to say:


7. prependTo ()
Description: Adds all paragraphs to the element with the ID value foo.

HTML code:

I wowould like to say:

JQuery code: $ ("p"). prependTo ("# foo"); Result:

I wowould like to say:


** 6 **. 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.
    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 ()
    User leaves 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 the click and change event function () {alert ('hello ');});


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

    $ ("P"). one ("click", function () {alert ("Hello"); // only run once, and will not run later });

    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 harmful link e. preventDefault (); // block opening $ (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 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.

    Several common filter selectors:

    Filter (): filter the set of elements that match the specified expression. This method is used to narrow the matching range. Multiple Expressions separated by commas
    Description: The sub-element containing ol is retained.

    HTML code:

    1. Hello

    How are you?

    JQuery code:

    $("p").filter(function(index) { return $("ol", this).length == 0;});

    Result:

    How are you?

    Silce (): select a matched subset.

    Description: select the first p element.

    HTML code:

    Hello

    cruel

    World

    JQuery code:

    $("p").slice(0, 1).wrapInner("");

    Result:

    Hello

    Subsequent Updates ......


    How to Use JQuery CDN? We recommend that you use the official CDN node. The Code is as follows:

     

    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.