Basic jQuery tutorial and basic jquery tutorial

Source: Internet
Author: User

Basic jQuery tutorial and basic jquery tutorial

This article describes jQuery's operations on elements, including basic operations, selection of elements to be operated, and processing of DOM elements. It has good reference value for jQuery learning. Share it with you for your reference. The specific analysis is as follows:

1. Basics

Jquery object set:

$ (): Jquery object set

Obtain the elements in the jquery object set:

Use indexes to retrieve javascript elements in the wrapper:

var temp = $('img[alt]')[0]

Use the get method of jquery to obtain the javascript elements in the jquery object set:

var temp = $('img[alt]').get(0)

Use the jquery eq method to obtain jquery object elements in the jquery object set:

$ ('Img [alt] '). eq (0)
$ ('Img [alt] '). first ()
$ ('Img [alt] '). last ()

Convert a jquery object set to a javascript array:

var arr = $('label+button').toArray()

All button elements at the same level after the label are converted into javascript arrays.

Index of the jquery object set:
Var n = $ ('img '). index ($ ('img # id') [0]) Note: The index () parameter is a javascript element.
Var n = $ ('img '). index ('img # id') is equivalent to returning-1 if the previous row cannot be found.
Var n = $ ('img '). index () to obtain the img index in the same level element

Add more jquery object sets to the jquery object set:
Use commas:

$('img[alt],img[title]')

Use the add method:

$('img[alt]').add('img[title]')

Different methods are used for different jquery objects:

$('img[alt]').addClass('thickBorder').add('img[title]').addClass('');

Add new elements to the jquery object set:

$('p').add('<div></div>');

Delete the elements in the jquery object set:

$('img[title]').not('[title*=pu]')$('img').not(function(){return !$(this).hasClass('someClassname')})

Filter jquery object sets:
$ ('Td '). filter (function () {return this. innerHTML. match (^ \ d + $)}) filter td containing numbers

Get a subset of jquery object sets

$ ('*'). Slice () contains the first four elements of the new jquery object set
$ ('*'). Slice (4) New jquery object set containing the first four elements
$ ('Div '). has ('img [alt]')

Convert the elements in the jquery object set:

var allIds = $('div').map(function(){ return (this.id==undefined) ? null : this.id;}).get();

The above example can be converted to a javascript Array Through the get method.

Traverse the elements in the jquery object set:

$ ('Img '). each (function (n) {this. alt = 'this is the [' + n + '] image. The image id is' + this. id;}) $ ([1, 2, 3]). each (function () {alert (this );})

Get the jquery object set using the relationship between elements:

$ (This). closest ('div '), for example, in which div the trigger button occurs
$ (This). siblings ('button [title = "Close"] ') All same-level elements, excluding
$ (This). children ('. someclassname') All child node elements, excluding repeated child nodes
$ (This). closest ('') near the ancestor Element
$ (This). contents () is a jquery object set composed of element content. For example, you can obtain the <iframe> element content.
$ (This). next ('. someclassname') next same level element
$ (This). nextAll () all peer Elements
$ (This). nextUntil ('. someclassname') all peer elements after the target Element
$ (This). offsetParent () parent element closest to the jquery object set
$ (This). parent () direct parent Element
$ (This). parents () All parent Elements
$ (This). parrentsUntil () All parent elements until the target parent Element
$ (This). prev () a sibling Element
All sibling elements before $ (this). prevAll ()
$ (This). All sibling elements before prevTntl () until the target Element

Other methods for getting jquery object sets:

$(this).find(p span)

Determine whether a jquery object set is used:

var hasImg = $('*').is('img');

Jquery method:

$ (). Hide ()
$ (). AddClass ('')
Contents ().html ('')
$ ('A'). size () element quantity

Jquery selector:

$ ('P: even ')
$ ('Tr: nth-child (1 )')
$ ('Body> div ') direct sub-element
$ ('A [href =$ = 'pdf ']') Select
$ (Div: has (a) Filter

Jquery functions:

$. Trim ()
Jquery execution time:
$ (Document). ready (function (){});
$ (Function (){});

Create a DOM element:

$('<p></p>').insertAfter();$('',{ src: '', alt: '', title: '', click: function(){}}).css({ cursor:'pointer', border:'', padding:'', backgroundColor:'white'}).append('');

Jquery extension:

$.fn.disable = function(){ return this.each(function(){ if(this.disabled != null) this.disabled = true; })};$('').disable();

Check whether the jquery test element exists:

If (item) () {} else {} loose Test
If (item! = Null) Recommended test, can distinguish null from undefined

2. Select the elements to operate

Based on Tag Name: $ ('A ')
Based on id: $ ('# id ')
Based on the class name: $ ('. someclassname ')
Meet multiple conditions: $ ('a # id. someclassname') or $ ('div, span ')
All subnodes of an element: $ (p a. someclassname)
Direct subnode of an element: $ (ul. myList> li)
Based on the property name:
$ (A [href ^ = 'HTTP: // ']) starts...
Ended...
$ (Form [method]) form containing the method attribute
$ (Intput [type = 'text'])
$ (Intput [name! = ''])
$ (Href * = 'some') contains

The first element after an element: $ (E + F) matches F, and F is the first element after E.

An element after an element: $ (E ~ F) matches F, and F is an element after E.

Location:

$ (Li: first) The first li
$ (Li: last) The last li
$ (Li: even) an even number of rows li
$ (Li: odd) odd line li
$ (Li: eq (n) indicates the nth element. The index starts from 0.
$ (Li: gt (n) the element after the nth element. The index starts from 0.
$ (Li: lt (n) indicates the element before the nth element. The index starts from 0.
$ (Ul: first-child) The first li in the list
$ (Ul: last-child) The last li in the list
$ (Ul: nth-child (n) the nth li in the list
$ (Ul: only-child) ul without brother li
$ (Ul: nth-child (even) indicates the even number of rows in the list. The odd indicates the counting row li.
$ (Ul: nth-child (5n + 1) li in the list divided by 5

Filter:

$ (Input: not (: checkbox ))
$ (': Not (img [src * = "dog"])')
$ ('Img: not ([src * = "dog"]) ')
$ (Div: has (span ))
$ ('Tr: has (img [src $ = "pu.png"]) ')
$ (Tr: animated) tr in the animation state
$ (Input: button) includes the Input values of the type buttons, reset, and submit.
$ (Input: checkbox) is equivalent to $ (input [type = checkbox])
$ (Span: contains (food) span containing text food
$ (Input: disabled) disabled
$ (Input: enabled) enabled
$ (Input: file) is equivalent to $ (input [type = file]).
$ (: Header) h1 to h6
$ (Input: hidden)
$ (Input: image) is equivalent to $ (input [type = image])
$ (: Input) includes input, select, textarea, And button elements.
$ (Tr: parent)
$ (Input: password) is equivalent to $ (input [type = password])
$ (Input: radio) is equivalent to $ (input [type = radio])
$ (Input: reset) is equivalent to $ (input [type = reset]) or $ (button [type = reset])
$ ('. Clssname: selected ')
$ (Input: submit) is equivalent to $ (input [type = submit]) or $ (button [type = submit])
$ (Input: text) is equivalent to $ (input [type = text])
$ (Div: visible)

3. Process DOM elements

Operation element attributes:

$('*').each(function(n){ this.id = this.tagName + n;})

Get property value:

$('').attr('');

Set the property value:

$ ('*'). Attr ('title', function (index, previusvalue) {return previusvalue + 'I am element' + index + 'and my name is' + this. id;}) // set the value for an attribute $ ('input '). attr ({value: '', title:''}); // you can specify multiple attributes.

Delete attributes:

$('p').removeAttr('value');

Open all links in a new window:

$('a[href^="http://"]').attr('target',"_blank");

Avoid multiple forms:

$("form").submit(function(){ $(":submit", this).attr("disabled","disabled");})

Add Class Name:

$('#id').addClass('')

Delete Class Name:

$('#id').removeClass('')

Switch Class Name:

$('#id').toggleClass('')

Delete a class name if it exists. If it does not exist, add a class name.
Determine whether the class name is included:

$('p:first').hasClass('') $('p:first').is('')

Returns the list of class names in array format:

$.fn.getClassNames = function(){ var name = this.attr('someclsssname'); if(name != null){ return name.split(" "); } else { return []; }}

Set style:

$('div.someclassname').css(function(index, currentWidth){ return currentWidth + 20;});$('div').css({ cursor: 'pointer', border: '1px solid black', padding: '12px 12px 20px 20x', bacgroundColor: 'White'});

Dimension:

$ (Div). width (500)
$ ('Div '). height ()
$ ('Div '). innerHeight ()
$ ('Div '). innerWidth ()
$ ('Div '). outerHeight (true)
$ ('Div '). outerWidth (false)

Positioning:

$ ('P'). offset () relative to reference position of the document
$ ('P'). position () offset relative position of the parent Element
$ ('P'). scrollLeft () offset value of the horizontal scroll bar
$ ('P'). scrollLeft (value)
$ ('P'). scrollTop ()
$ ('P'). scrollTop (value)

Related element content:

Certificate ('p'0000.html ()
Certificate ('p'0000.html ('')
$ ('P'). text ()
$ ('P'). text ('')

Append content

Append an html segment at the end of the element:

$('p').append('<b>some text</b>');

Existing elements in the dom at the end of the element:

$('p').append($(a.someclassname))

Append at the beginning of the element:

$("p").prepend()

Append an element before it:

$("span").before()

Append the following elements:

$("span")after()

Append the content to the end:

appendTo(targets)

Append content to the beginning:

prependTo(targets)

Append the content to the front of the element:

insertBefore(targets)

Append the content to the end of the element:

$('<p></p>').insertAfter('p img');

Package elements:

$ ('A. someclassname'). wrap ("<div class = 'hello'> </div> ")
$ ('A. someclassname'). wrap ($ ("div: first") [0])
$ ('A. someclassname'). wrapAll ()
$ ('A. someclassname'). wrapInner ()
$ ('A. someclassname'). unWrap ()

Delete element:

$ ('. Classname'). remove () deletes an element. Events and data bound to the element are also deleted.
$ ('. Classname'). detach () deletes elements, but retains events and Data
$ ('. Classname'). empty () does not delete the element, but clears the element content.

Copy element:

$('img').clone().appendTo('p.someclassname')
$('ul').clone().insertBefore('#id')

Replacement element:

$('img[alt]').each(function(){ $(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');})$("p").replaceAll("<b></b>")

Values of form elements:

$ ('[Name = "radioGroup"]: checked '). val () gets the value of the single-choice button. If no value is selected, undefinedvar checkboxValues =es ('[name = "checkboxGroup"]: checked') is returned '). map (function () {return $ (this ). val ();}). toArray (); // obtain the value of the multiple selection box

For <select id = "list" multiple = "multiple"> arrays returned by using $ ('# list'). val ()
$ ('Input'). val (['one', 'two', 'three ']) if the single sequence or check box matches the element in the array, select the status.

I believe this article provides some reference value for jQuery program design.


How to operate HTML elements using jQuery

JQuery Selector

The jQuery element selector and attribute selector allow you to select HTML elements by Tag Name, attribute name, or content.
The selector allows you to operate on HTML element groups or individual elements.
In html dom terminology:
The selector allows you to operate a DOM element group or a single DOM node.

Selector instance Selection

* $ ("*") All elements
# Id $ ("# lastname") id = "lastname" element
. Class $ (". intro") All class = "intro" Elements
Element $ ("p") All <p> Elements
. Class. class $ (". intro. demo") All class = "intro" and class = "demo" Elements
     
: First $ ("p: first") first <p> element
: Last $ ("p: last") last <p> element
: Even $ ("tr: even") All even <tr> Elements
: Odd $ ("tr: odd") All odd <tr> Elements
     
: Eq (index) $ ("ul li: eq (3)") The fourth element in the list (index starts from 0)
: Gt (no) $ ("ul li: gt (3)") list elements with an index greater than 3
: Lt (no) $ ("ul li: lt (3)") list elements whose index is less than 3
: Not (selector) $ ("input: not (: empty)") All input elements not empty
     
: Header $ (": header") All title elements : All animation elements of animated
     
: Contains (text) $ (": contains ('w3school')") contains all elements of the specified string
: Empty $ (": empty") all elements of nodes without child (element)
: Hidden $ ("p: hidden") All hidden <p> Elements
: Visible $ ("table: visible") all visible tables
     
S1, s2, s3 $ ("th, td,. intro") All elements with matching Selection
     
[Attribute] $ ("[href]") All elements with the href attribute
[Attribute = value] $ ("[href = '#']") the value of all href attributes is equal to the element "#".
[Attribute! = Value] $ ("[href! = '#'] ") The value of all href attributes is not equal to" # & quot ...... the remaining full text>

How to locate and operate several page elements in jquery

JQuery provides two methods to select html elements. The first method is to combine CSS with the Xpath selector to form a string to be transmitted to the jQuery Constructor (for example: $ ("div> ul a"); the second is to use several methods of the jQuery object ). These two methods can also be combined for hybrid use. Let's try to select and modify the first ordered list in our test.html code. in the beginning, we need to select the list itself. This list has an ID called "orderedlist", and the common javascript syntax is document. getElementById ("orderedlist "). in jQuery, the Code is as follows: $ (document ). ready (function () {$ ("# orderedlist "). if addClass ("red" has been added to orderedlist, after you refresh test.html, you will see that the background color of the first ordered list has changed to blue, but the second ordered list has not changed. the Code is as follows: $ (document ). ready (function () {$ ("# orderedlist> li "). addClass ("blue") ;}); this The Style "blue" is appended to li in all orderedlist ". If you want to implement style switching when you place the cursor over the li object and when you move it away, it takes effect only on the last element of the list. $ (Document ). ready (function () {$ ("# orderedlist li: last "). hover (function () {$ (this ). addClass ("green") ;}, function () {$ (this ). removeClass ("green") ;}); find () allows you to search for conditions in the selected element, so $ ("# orderedlist ). find ("li") is like $ ("# orderedlist li. The each () method iterates all the li resources and can perform more processing on this basis. Most methods, such as addClass (), can use their own each (). Html () is used to obtain the html text of each li, append some text, and set it as the html text of li. JQuery provides two methods: filter () and not. Filter () uses a filter expression to reduce the selected items that do not match. not () is used to cancel all selected items that match the filter expression. consider an unordered list. You want to select all li elements without ul sub-elements. $ (Document ). ready (function () {$ ("li "). not (": has (ul)" bar .css ("border", "1px solid black"); // The original version is $ ("li "). not ("[ul]" ).css ("border", "1px solid black") ;}); this code Selects all li elements, then remove the li element with UL sub-elements. Click the full text of ...... the remaining text>

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.