Front-end: jQuery,: jQuery

Source: Internet
Author: User

Front-end: jQuery,: jQuery

1. jQuery Introduction

Ii. Advantages of jQuery

III. Basic jQuery syntax

1. Search for tags

1) Selector

(1) id Selector

$("#id")

(2) Tag Selector

$("tagName")

(3) class selector

$(".className")

(4) combination Selector

$ ("# Id,. className, tagName ")

// All element selectors $ (""*"")

(5) Hierarchical Selector

$ ("X y"); // all descendant y of x (son and Sun) $ ("x> y"); // All son y of x (son) $ ("x + y") // locate all y $ ("x ~ Y ") // all the brothers after x y

(6) Basic Filter

: First // first: last // the last one: eq (index) // The element whose index is equal to the index: even // matches all the elements whose index values are even, counting starts from 0: odd // matches all elements with an odd index value, and counting starts from 0: gt (index) // matches all elements greater than the given index value: lt (index) // match all elements smaller than the given index value: not (element selector) // remove all tags that meet the not condition: has (element selector) // select all the tags that contain one or more tags (from the descendant element)

(7) attribute Selector

[Attribute] [attribute = value] // attribute equals to [attribute! = Value] // attribute is not equal

(8) expression Filtering

:text:password:file:radio:checkbox:submit:reset:button

(9) form object attributes

: Enabled: disabled // invisible: checked: selected // The selected

2) Filter

(1) next element

$("#id").next()$("#id").nextAll()$("#id").nextUntil("#i2")

(2) last element

$("#id").prev()$("#id").prevAll()$("#id").prevUntil("#i2")

(3) Father Element

$ ("# Id "). parent () $ ("# id "). parents () // search for all parent elements of the current element $ ("# id "). parentsUntil () // finds all parent elements of the current element until the matched element is met.

(4) son and brother Elements

$ ("# Id"). children (); // sons $ ("# id"). siblings (); // brothers

(5) Search for elements

$ ("# Id"). find () // search for all elements that match the specified expression.

(6) Others

. First () // obtain the first Matching Element. last () // obtain the last matched element. not () // Delete the elements that match the specified expression from the set of matching elements. has () // retain the elements that contain specific offspring and remove those that do not contain the specified descendant.

2. Operation tag

1), style operations

Style

AddClass (); // Add the specified CSS class name. RemoveClass (); // removes the specified CSS class name. HasClass (); // determines whether toggleClass () exists in the style store; // switch the CSS class name. If yes, remove it. If no, add it.

Example: switch lamp and modal box

CSS

Css ("color", "red") // DOM operation: tag. style. color = "red"

Example:

$ ("P" ).css ("color", "red"); // set the font of all p labels to red

Location:

Offset () // obtain the relative offset of the matching element in the current window or set the position () of the element. // obtain the scrollTop () offset of the matching element relative to the parent element () // obtain the scrollLeft () offset of the matching element relative to the top of the scroll bar. // obtain the offset of the matching element relative to the left of the scroll bar.

Note:

.offset()This method allows us to retrieve the current position of an element relative to the document.

And.position()The difference is:.position()Is the displacement relative to the parent element.

Size:

height()width()innerHeight()innerWidth()outerHeight()outerWidth()

2) text operations

HTML:

Html () // obtain the html content of the First Matching Element html (val) // set the html content of all matching elements

Text value:

Text () // get the content of all matching elements text (val) // set the content of all matching elements

Value:


Val () // get the current value of the First Matching Element val (val) // set the values of all matching elements val ([val1, val2]) // set the checkbox and select values

Obtain the value of the selected checkbox or radio:

$ ("Input [name = 'name']: checked"). val ()

3) attribute operations

Used for ID and other or custom attributes:

Attr (attrName) // returns the attribute value attr (attrName, attrValue) of the First Matching Element // sets an attribute value attr ({k1: v1, k2: v2}) for all matching elements }) // set multiple attribute values for all matching elements removeAttr () // delete an attribute from each Matching Element

For checkbox and radio:

Prop () // get the property removeProp () // remove the property

Ps:

When attr is used in jQuery of 1.x and 2.x to assign values to the checkbox, a bug occurs. This problem is not found in jQuery of 3.x. For compatibility, we try to use a specific prop () when dealing with checkbox and radio. Do not use attr ("checked", "checked ").

<input type="checkbox" value="1"><input type="radio" value="2"><script>  $(":checkbox[value='1']").prop("checked", true);  $(":radio[value='2']").prop("checked", true);</script>

4), Document Processing

Add to the end of a specified Element

$ (A). append (B) // append B to A $ (A). appendTo (B) // append A to B

Add to the front of a specified Element

$ (A). prepend (B) // bring B to A $ (A). prependTo (B) // bring A to B

Add to the end of the specified Element

$ (A). after (B) // put B behind A $ (A). insertAfter (B) // put A behind B

Add to the front of the specified Element

$ (A). before (B) // put B in front of A $ (A). insertBefore (B) // put A in front of B

Remove and clear elements

Remove () // delete all matched elements from the DOM. Empty () // delete all child nodes in the matched element set.

Replace

replaceWith()replaceAll()

Clone

clone()

3. Events

1) common events

click(function(){...})hover(function(){...})blur(function(){...})focus(function(){...})change(function(){...})keyup(function(){...})

2) event binding

. On (events [, selector], function () {}) // events: Event // selector: selector (optional) // function: event processing function

3) Remove events

. Off (events [, selector] [, function () {}]) // off () method to remove the event handler bound with. on. // Events: Event // selector: selector (optional) // function: event processing function

4) Organize subsequent event execution

// Return false, for example, blocking form submission. For events defined in DOM such as click and keydown '. on () 'method to bind events, but the events defined in jQuery such as 'hover' cannot be used '. the on () 'method is bound. To bind a hover event handler using event delegation, You can bind the event in two steps by referring to the following code: $ ('ul '). on ('mouseenter', 'lil', function () {// bind the mouse to the event $ (this ). addClass ('hover ') ;}); $ ('ul '). on ('mouseleave ', 'lil', function () {// bind the mouse to draw events $ (this ). removeClass ('hover ');});

5) load the page

Bind a function to be executed when the DOM is ready for query and operation. This is the most important function in the event module, because it can greatly improve the response speed of web applications.

$ (Document). ready (function () {// write your JS code here ...})

6) event Delegation

Event delegation uses the parent tag to capture sub-tag events based on the event bubbling principle.

// The edit and delete buttons of each row in the table can trigger corresponding events. $ ("Table"). on ("click", ". delete", function () {// events bound to the delete button })

4. animation effect

// Basic show ([s, [e], [fn]) hide ([s, [e], [fn]) toggle ([s], [e], [fn]) // slide slideDown ([s], [e], [fn]) slideUp ([s, [e], [fn]) slideToggle ([s], [e], [fn]) // fade-in and fade-out fadeIn ([s], [e], [fn]) fadeOut ([s], [e], [fn]) fadeTo ([[s], o, [e], [fn]) fadeToggle ([s, [e], [fn]) // custom (learn more) animate (p, [s], [e], [fn])

5, each

1), jQuery. each (collection, callback (indexInArray, valueOfElement )):

A common iteration function that can be used to seamlessly iterate objects and arrays. An array and an object similar to an array use a length attribute (such as a parameter object of a function) to iterate the numeric index, from 0 to length-1. Other objects are iterated through their attribute names.

Li = [10, 20, 30, 40] $. each (li, function (I, v) {console. log (I, v); // index is the index and ele is the specific element of each loop .})

2),. each (function (index, Element )):

Traverses a jQuery object and executes a function for each matching element.

// Add foo $ ("li"). each (function () {$ (this). addClass ("c1") ;}) for each li tag ");});

.each()Method is used to iterate every DOM element in the jQuery object. During each callback function execution, the current number of cycles is passed as the parameter (counting starts from 0 ). Because the callback function is triggered in the context where the current DOM element is the context, the keywordthisAlways point to this element.

Terminate an each loop

return false;

6. data ()

Store any related data on all elements in the matched element set or return the value of the given name of the first element in the matched element set.

. Data (key, value ):

Description: stores any related data on matching elements.

$ ("Div"). data ("k", 100); // save a k name for all div labels with a value of 100

. Data (key ):

Description: return the data storage value of the given name of the first element in the matched element set-pass.data(name,value)OrHTML5 data-*Attribute settings.

$ ("Div"). data ("k"); // return the value of "k" saved in the first div label

. RemoveData (key ):

Description: removes data stored on an element. If the key parameter is not added, all stored data is removed.

$ ("Div"). removeData ("k"); // remove the element to store the data corresponding to k

 

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.