JQuery selector and filter introduction _ jquery

Source: Internet
Author: User
Anyone who has used AJAX technology knows the famous JQuery. Although I have watched AJAX videos before, I was still vague about WEB applications at that time, but I don't know how HTML, JSP, and Servlet work, I don't even know what JQuery is packaging. Today's learning combined with yesterday's JavaScriptDOM content makes me very clear about this. JQuery principle: "write less, do more.", which fully demonstrates its skill in simplifying the use of JavaScriptDOM programming!
Each teacher has his/her own teaching method, which may slightly change depending on the content of the professor. He is a very experienced software teacher and previously trained at a software company in Dalian. After years of summarization, he has developed his own mature teaching methods. I like this method very much! You can try it yourself! Haha ~~
From learning Java WEB and Struts1 to the current JavaScript, I have found the core of WEB application development-MVC. Yes, it is MVC. In fact, MVC should be created based on the core of the WEB. Isn't it! The complete set of tools are operations on the visual layer, control layer, and data model layer respectively. It seems that I have found some feelings now, because when I learned servlet, I knew it could process user requests, and the teacher could learn what I said. But now I have an idea. No matter what you say, I know what layer it should be used for and what purpose it will improve my learning efficiency. This is a very good growth! It will be of great help for future growth.
Then there will be no more scattered knowledge, and then we will start to build projects. Two words, fast and refreshing! OK.
I. JQuery and JavaScript
1. JavaScript Library
Anyone who has used JavaScriptDOM should know (for example, yesterday's exercise) that using JSDOM to perform page operations is very troublesome. Such as obtaining, modifying, and adding subnodes. What if I operate on a complex page? OK, the JavaScript library was born.
Currently, common JavaScript libraries include:

2. JQuery Introduction
JQuery is another excellent JavaScript library after Prototype.
JQuery philosophy: write less, do more.
JQuery advantages: lightweight, powerful selector, excellent DOM operation encapsulation, reliable event processing mechanism, perfect Ajax, excellent browser compatibility, and chain operation .......

Ii. JQuery objects and DOM objects
1. JQuery object
The JQuery object uses "$ (" DOMObj ")" to wrap the DOM object. In general, "$" is added before the JQuery object to distinguish it from the DMO object. It is already a recognized naming convention. JQuery objects cannot call attributes and methods of DOM objects. Similarly, DOM objects cannot call attributes and methods of JQuery objects.

2. convert a JQuery object to a DOM object
What if I want to use a JQuery object to call the DOM object method? The JQuery object should be converted into a DOM object. The JQuery object is an array object, which is very special. Therefore, you only need to call JQueryObj [x] Or JQueryObj. get (X); to convert it to a DOM object.

3. convert a DOM object to a JQuery object
Use "$ (" DOMObj ")" to wrap the DOM object.

Iii. JQuery Selector
Selector is the foundation of JQuery. In JQuery, event processing, DOM traversal, and Ajax operations depend on the selector. This is also the focus of our learning today.

1. Basic Selector
The basic selector is the most common selector in JQuery and the simplest selector. it searches for DOM elements by element id, class, and tag signature. This is very important. The following content is based on this and upgraded step by step.
1). "$ (" # id ")" to obtain the element specified by the id. The id is globally unique, so it has only one member.
2). "$ (". class ")" to obtain the elements specified by the class. Different elements can have the same class attribute, so they may have multiple members.
3). "$ (" element ")" to obtain the specified element (element name, such as p and table). It may have multiple members.
4). "$ (" * ")" to get all elements, which is equivalent to document.
5). "$ (" selector1, selector2 ,..., SelectorN ")", which combines the elements matched by each selector and returns them together. Returns the set that selector1 matches + the set that selector2 matches +... + SelectorN matched set.

2. Hierarchical Selector
What is a hierarchy? A hierarchy is a node of a parent-child relationship or sibling relationship. The hierarchy selector is used to obtain the Parent and Child Nodes and sibling nodes of the specified element.
1). "$ (" ancestor descendant ")" to get all elements under the ancestor element.
2) "$ (" parent> child ")" to obtain all child elements (including only the first child element) under the parent element ).
3). "$ (" pre + next ")" to obtain the last sibling element following the pre element.
4). "$ (" pre ~ Siblings ")" to obtain all the sibling elements behind the pre element.

3. Filter Selector
Filter? You must add filtering conditions. ":" Is used to add filtering conditions. For example, "$ (" p: first ")" returns the first p element in the p element set. "first" is the filtering condition.
Based on different filtering rules, the filter selector can be divided into basic filtering, content filtering, visibility filtering, attribute filtering, subelement filtering, and form object attribute filtering selector.

1). Basic filter Selector
A) ": first", select the first element. Do not forget that it is also placed in a set! Because JQuery is a collection of DOM objects. For example, "$ (" tr: first ")" returns the first tr element of all tr elements, which are still saved in the set.
B) ": last", and select the last element. For example, "$ (" tr: last ")" returns the last tr element of all tr elements, which are still saved in the set.
C) ": not (selector)" removes all elements that match the given selector. For example, "$ (" input: not (: checked) ")" returns all input elements, but removes the selected elements (single-choice and multi-choice boxes ).
D) ": even", which selects the even elements of all elements. Because the JQuery object is a set, the even number here refers to the index of the set, and the index starts from 0.
E) ": odd": select the odd number of all elements, and the index starts from 0.
F) ": eq (index)". Select the element of the specified index. The index starts from 0.
G) ": gt (index)". Select an element whose index is greater than the specified index. The index starts from 0.
H) ": lt (index)". Select the element whose index is smaller than the specified index. The index starts from 0.
I) ": header", select all title elements, such as hq and h2.
J) ": animated", which selects all animation elements currently being executed.

2). Content Filtering Selector
It is an operation on elements and text content.
A) ": contains (text)", and select the elements that contain text content.
B) ": empty": select an empty element that does not contain child elements or text nodes.
C) ": has (selector)" to select the elements that contain the elements matching the selector.
D) ": parent", and select the elements that contain child elements or text nodes. (It is a parent node)

3). Visibility filter Selector
Select an element based on its visibility and invisibility status.
": Hidden" to select all invisible elements.
": Visible": select all visible elements.
Visible selector: hidden not only contains elements whose style attribute display is none, but also contains text hidden fields ( ) And visible: elements such as hidden.

4). Attribute filter Selector
Select an element based on its attributes.
A) "[attribute]", select the element that owns this attribute.
B) "[attribute = value]", selects all elements whose specified attribute value is value.
C) "[attribute! = Value] ", select all elements whose property value is not value.
D) "[attribute ^ = value]" and select all elements whose attribute values start with value.
E) "[attribute $ = value]", and select all elements whose attribute values end with value.
F) "[attribute * = value]", and select all elements whose attribute values contain value.
G) "[selector1] [selector2]… [SelectorN] ", composite selector, first returns set A by [selector1], and then returns Set B by going through [selector2, set B and then select the returned result set through [selectorN.

5). Child element filter Selector
First, the name is used to select sub-elements of an element.
A) ": nth-child (index/even/odd)", select the index-based elements, the index-based elements with an even number, and the index-based elements with an odd number.
L nth-child (even/odd): selects an element whose index value under each parent element is an even (odd) number.
L nth-child (2): select an element with an index value of 2 under each parent element.
L nth-child (3n): select an element whose index value under each parent element is a multiple of 3.
L nth-child (3n + 1): You can select an element whose index value is 3n + 1 for each parent element.
B) ": first-child", and select the first child element.
C) ": last-child", and select the last child element.
D) ": only-child". Select a unique child element. Its Parent element only has this child element.

6). form filter Selector
Select the filter selector for the form element.
A) ": input", select all , , AndElement.B) ": text". Select all text box elements.C) ": password". Select all the elements in the password box.D) ": radio". Select all single-member elements.E) ": checkbox", which selects all the multiple selection box elements.F) ": submit", select all the submit button elements.G) ": image", select all image button elements.H) ": reset", and select all reset button elements.I) ": button", select all button elements.J) ": file", select all file upload domain elements.K) ": hidden", select all invisible elements.7). form object attribute filter SelectorSelect the filter selector for the form element attribute.": Enabled" to select all available elements.": Disabled" to select all unavailable elements.": Checked": select all selected elements, such as single-check boxes and check boxes.": Selected": select all selected items, as shown in the following drop-down list box and list box.Iv. DOM operations in JQueryAn interface unrelated to browsers, platforms, and languages. You can use this interface to easily access all the standard components on the page.DOM Core: DOM Core is not specialized in JavaScript. It can be used by any programming language that supports DOM. It is not only used to process web pages. It can also be used to process any document written in markup language, such as XML.Html dom: When scripting HTML files with JavaScript and DOM, there are many properties dedicated to HTML-DOM.CSS-DOM: for CSS operations, in JavaScript, CSS-DOM is primarily used to get and set various attributes of a style object.1. Search for nodesSee the "Basic selector" above ".2. Create a nodeUse the JQuery factory function to create a new node: var $ newNode = $ ("Hi!"), And then insert the new node to the specified Element Node.3. Insert a nodeInsert the newly created node or acquired node to the specified position."$ Node. append ($ newNode)" to append the end to the internal end of each matching element. For example, "$ (" p "). append ("Hello");" Will"Hello"Add to the end of" p."$ NewNode. appendTo ($ node)" to append the new element to the end of each matching element."$ Node. prepend ($ newNode)" to append the start point to the end of each matching element. For example, "$ (" p "). prepend ("Hello");" Will"Hello"Added to the start point of" p."$ NewNode. prependTo ($ node)" to append the new element to the beginning of each matching element."$ Node. after ($ newNode)" inserts content after each matching element. For example, "$ (" p "). after ("Hello");" Will"HelloInsert it to the back of p. They are brothers."$ NewNode. insertAfter ($ node)" inserts a new element after each matching element."$ NewNode. before ($ node)" inserts content before each matching element. For example, "$ (" p "). before ("Hello");" Will"HelloInsert to the front of p. They are brothers."$ Node. insertBefore ($ newNode)" inserts a new element before each matching element.Note: If the inserted node is not newly created, the insert operation changes to the move operation. Therefore, the clone node should be used before such a node is inserted.4. delete a nodeRemoves all matched elements from the DOM. For example, "$ (" p "). remove (". hello ");" deletes the p element for which the class attribute value is hello, and all the elements under it.Clear all matched elements from the DOM. For example, "$ (" p "). empty ();" clears all p elements and all elements under it.5. Copy a nodeClone the matched DOM element. For example, "$ (" p "). clone ();" returns the cloned copy without any action. To clone DOM events together, use "$ (" p "). clone (true );".6. Replace nodesReplaces all matched elements with specified HTML or DOM elements. For example, $ ("p"). replaceWith ("Paragraph.");, Replace all p elements"Paragraph.".Returns to replaceWith: $ ("Paragraph."). ReplaceAll (" p ");.7. Package nodesWrap (): wrap the specified node with other labels. This method is useful for inserting additional structured tags in a document without damaging the semantics of the original document. For example, "$ (" p "). wrap ("");". Each p element is enclosed in.WrapAll (): wrap all matching elements with one element. The wrap () method is to wrap all elements separately. For example, "$ (" p "). wrapAll ("");", Wrap all p elements.WrapInner (): Wrap child content (including text nodes) of each Matching Element with other structured tags. For example, "$ (" p "). wrapInner ("");",Wrapped by every p element.8. attribute settingsAttr (): Get and set attributes.When a parameter is passed for this method, it is used to obtain the specified attribute of an element. For example, "$ (" img "). attr (" src ");" gets the src attribute value of the img element.When two parameters are passed for this method, that is, the attribute value is set for an element. For example, "$ (" img "). attr (" src "," test.jpg ");", set the src attribute value of the img element to test. jsp.Many methods in jQuery are implemented and set by a function. For example, attr (), html (), text (), val (), height (), width (), css (), and so on.RemoveAttr (): deletes a specified attribute of a specified element.9. style operationsYou can use "attr ()" to set or retrieve css styles.Append style: addClass (). For example, "$ (" p "). addClass (" selected ");", append the "selected" style to all P elements.Remove style: removeClass () --- delete all or specified classes from matched elements. For example, "$ (" p "). removeClass (" selected ");" deletes "selected" from all P elements ".Switching style: toggleClass () --- controls repeated switching of styles. If the class name exists, delete it. If the class name does not exist, add it. For example, "$ (" p "). toggleClass ("selected"); ". If the" selected "style exists in all P elements, delete the" selected "style. Otherwise, add the" selected "style.Determines whether a style exists: hasClass () --- determines whether the element contains a class. If yes, true is returned; otherwise, false is returned. For example, "$ (this). hasClass (" protected ")" to determine whether the current node has a "protected" style.10. set or obtain HTML, text, and valuesRead and set the HTML content of an element: html (). This method can be used for XHTML, but not for XML documents.Read and set the text content in an element: text (). This method can be used for both XHTML and XML documents.Read and set the value in an element: val (). This method is similar to the value attribute in JavaScript. For the text box, drop-down list box, single comment this method can return the value of the element (multiple select box can only return the first value ). If you select multiple drop-down lists, an array containing all selected values is returned.11. Common Methods for Traversing nodesGets a set of all child elements that match an element: children (). This method takes into account only the first child element instead of any child element.Obtains the set of sibling elements next to the Matching Element (but only one element in the Set): next ().Obtains the set of sibling elements adjacent to the Matching Element (but only one element in the Set): prev ().Obtain all the sibling elements before and after the matching element: siblings ().12. CSS-DOM operationGet and set the style attribute of the element: css ().Get and set the element transparency: opacity () attribute.Obtain and set the element height, width: height (), width (). When setting the value, if only a number is passed, the default unit is px. If you want to use another unit, you need to pass a string, for example, "$ (" p: first "). height (" 2em ")";Obtains the relative displacement of an element in the current window: offset (). The returned object contains two attributes: top and left. This method is only valid for visible elements.5. Events in JQuery 1. Load DOMAfter the page is loaded, the browser adds an event to the DOM element through JavaScript. In common JavaScript code, the window. onload method is usually used, and the $ (document). ready () method is used in JQuery. The simplified format in JQuery is "$ ()". When registering an event in window. onload, it can only be registered in one window. onload body. But with JQuery, you can register in multiple $ (document). ready () or $.2. Event bindingBind the matching element to the specified event. For example, yesterday we bound the event Method to window. onload: "$ (" p "). onclick (function () {alert ($ (this). text ());}); "In JQuery's $ (document ). in ready (), you can bind: "$ (" p "). click (function () {alert ($ (this ). text ());}); "Bind (), which can be bound as follows: $ (" p "). bind ("click", function () {alert ($ (this ). text ());});3. Merging eventsHover (): Simulate the cursor hover time. When the cursor moves to an element, the specified first function is triggered. When the cursor moves out of this element, the specified second function is triggered. For example, hover effect: $ ("td "). hover (function () {$ (this ). addClass ("hover") ;}, function () {$ (this ). removeClass ("hover ");});Toggle (): used to simulate continuous Mouse clicking events. Click an element for the first time to trigger the specified first function. When you click the same element again, the second function is triggered. If there are more functions, the function is triggered in turn, until the last one. For example, set the selection and non-selection effects of elements:$ ("Td "). toggle (function () {$ (this ). addClass ("selected");}, function () {$ (this ). removeClass ("selected ");});When toggle () is used without passing parameters, the effect is to switch the visible state of the element.4. Event bubblingThe event will follow the DOM hierarchies to keep up and stop the top.Solution: if false is returned in the event processing function, the event will stop bubbling. You can also stop the default behavior of elements.Currently, all UI interactions or events support this feature. If your event handler returns false, the event will be aborted and passed down. Returns true to continue to pass down.5. attributes of the event objectEvent object: when an event is triggered, the event object is created. To use an event in a program, you only need to add a parameter to the handler. Use some parameters in the event processing function. For example, to obtain the location of an event relative to the page: event. pageX, event. pageY, and event are parameters of the event processing function.6. Remove eventsRemove all click events on a button: $ ("btn"). unbind ("click ")Remove all events on a button: $ ("btn"). unbind ();One (): This method can bind a handler to an element. When the processing function is triggered once, the event is deleted immediately. That is, the event processing function is executed only once on each object.Vi. DOM animation in JQueryYou can set the display and hiding modes of DOM objects to produce animations.1. Hide and display non-animated effectsHide (): In an HTML document, calling the hide () method for an element changes the display style of the element to none. Code functions are the same as css ("display", "none.Show (): Change the display style of the element to the previous display status.Toggle (): switches the visible state of an element. If the element is visible, the switch is hidden. If the element is hidden, the switch is visible.2. Hide and display the transparency effect to achieve the animated Effect of fade in and out.FadeIn (), fadeOut (): only change the transparency of elements. FadeOut () reduces the opacity of an element within a specified period of time until the element completely disappears. FadeIn () is the opposite. For example, fade a paragraph into the form within 600 milliseconds: $ ("p"). fadeIn ("slow ");.FadeTo (): Adjust the opacity to the specified value (between 0 and 1) in an ascending manner ). And an optional callback function is triggered after the animation is complete. For example, adjust the transparency of a paragraph to 200 in 0.25 milliseconds. After the Animation ends, an "Animation Done" message box is displayed: "$ (" p "). fadeTo ("fast", 0.25, function () {alert ("Animation Done. ");});".3. Hide and display height effects to achieve slide and hide animation EffectsSlideDown (), slideUp (): Only the height of the element is changed. If the display attribute of an element is none, when the slideDown () method is called, the element is displayed from top to bottom. The slideUp () method is the opposite. elements are hidden from bottom to bottom. For example, slide a paragraph slowly for 600 milliseconds: $ ("p"). slideDown ("slow ");.SlideToggle (): switches the visibility of matching elements through height changes. For example, a paragraph is quickly slide up or down within 200 milliseconds. After the Animation ends, an "Animation Done" message box is displayed: "$ (" p "). slideToggle ("fast", function () {alert ("Animation Done. ");});".JavaScript and JQuery can be used to process the dynamic updates of the current page. Combined with CSS styles, a very beautiful UI can be made, even more beautiful than the desktop software UI. Writing and debugging JavaScript is very troublesome, so some companies have also produced simplified development specifically for JavaScript applications. For example, GWT produced by Google can write JavaScript like swing written in Java. It provides users with operations such as UI interfaces and events like swing and supports the core library of JAVA. Using GWT's own compiler, You can compile JAVA code into JavaScript code, CSS style files, and HTML.
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.