The 1th chapter on the realization of jquery
jquery has the following advantages:
- Lightweight
- a powerful selector;
- Excellent DOM operation encapsulation;
- Reliable event-handling mechanism;
- Perfect Ajax;
- Do not pollute top-level variables;
- excellent browser compatibility;
- Chain mode of operation;
- An implicit iteration;
- Separation of the behavior layer from the structural layer;
- Rich plug-in support;
- Perfect documentation;
- Open source.
The jquery object is the object that is generated after wrapping the DOM object through jquery.
You cannot use any method of a DOM object in a jquery object. Similarly, DOM objects cannot use the methods in jquery.
JQuery objects and Dom conversion of objects to each other
If the object being obtained is a jquery object, precede the variable with $, for example:
var $variable = jquery object;
If you get a DOM object, it is defined as follows:
var variable = dom object;
(1) jquery provides two ways to convert a jquery object into a DOM object, which is [index] and get (index).
(2) For a DOM object, you only need to wrap the DOM object with $ () to get a jquery object. The method is $ (DOM object).
With these methods, jquery objects and Dom objects can be converted to each other arbitrarily.
solving jquery conflicts with other libraries
(1) jquery library is imported after other libraries
After the other libraries and the jquery library have been loaded, you can call the Jquery.noconflict () function class at any time to transfer control of the variable $ to other JavaScript libraries.
(2) jquery libraries are imported before other libraries
If the jquery library is imported before other libraries, you can use jquery directly to do some jquery work. At the same time, you can use the $ () method as a shortcut to other libraries. There is no need to call the Jquery.noconflict () function.
2nd Chapter jquery Selector
JQuery the advantages of selectors
- A concise notation
- Supports CSS1 to CSS3 selectors
- The perfect processing mechanism
Using jquery to get an element that doesn't exist in a webpage does not make an error, which avoids some errors.
It is important to note, for example, that $ (' #tt ') gets the object forever, even if there is no such element on the page. Therefore, when you want to use jquery to check whether an element is on a Web page, you cannot use the following code:
if ($ (' #tt ')) {
Do something
}
Instead, the code should be judged based on the length of the element being fetched:
if ($ (' #tt '). Length > 0) {
Do something
}
or converted to DOM object to judge, the code is as follows:
if ($ (' #tt ') [0]) {
Do something
}
JQuery Selector Selector
The jquery selector is divided into basic selectors, hierarchical selectors, filter selectors, and form selectors.
The basic selector is the most commonly used selector in jquery and the simplest selector, which finds DOM elements by element ID, class, and tag name.
- #id match an element according to the given ID;
- The. class matches the element according to the given class name;
- Element matches elements according to the given element name;
- * Match all elements;
- selector1,selector2,,selectorn Returns the set of elements that each selector matches to.
Hierarchical selectors are a good choice if you want to get specific elements, such as descendant elements, child elements, neighboring elements, and sibling elements, through hierarchical relationships between DOM elements.
- Ancestor descendant selects all descendant (descendants) elements in the ancestor element;
- Parent > Child Selects the Children element under the parent element;
- Prev + Next selects the next element immediately after the Prev element;
- Prev ~ Siblings selects all siblings elements after the Prev element.
The filter selector primarily filters out the required DOM elements through specific filtering rules.
(1) Basic filter Selector
- : first SELECT element;
- : Last selected element;
- : Not (selector) removes all elements that match the given selector;
- : Even selects all elements with an even number, and the index starts at 0;
- : Odd Selection index is an odd number of all elements, the index starts from 0;
- : EQ (index) selects an element that is equal to index (index starts at 0);
- : GT (Index) selects an element with an index greater than index (index starting from 0);
- : LT (index) selects an element with an index that is less than index (index starting from 0);
- : Header selects all the caption elements, such as h1,h2,h3 and so on;
- : Animated selects all elements that are currently performing the animation;
- : Focus selects the element that currently takes focus.
(2) Content Filter Selector
The filter rules of the Content filter selector are mainly embodied in the child elements or text that it contains.
- : Contains (text) Select the element containing the text content "text";
- : Empty selects null elements that do not contain child elements or text;
- : Has (selector) selects the element that contains the element that the selector matches;
- :p arent Select elements that contain child elements or text.
(3) Visibility Filter Selector
- : Hidden selects all elements that are not visible;
- : Visible selects all visible elements.
In the visibility selector, you need to be aware of the selector: hidden, which includes not only elements of the style property display as "None", but also text hiding (<input> type= "hidden"/> and visibility: Elements such as hidden.
(4) Attribute filter Selector
- [attribute] Select the element that owns this property;
- [Attribute=value] Select the element with the value of the property as the values;
- [Attribute!=value] The value of the selected attribute is not equal to the element of value;
- [Attribute^=value] The element that selects the value of the attribute to start with "value";
- [Attribute$=value] The element that selects the value of the attribute to be terminated with value;
- [Attribute*=value] The value of the selected attribute contains the element of value;
- [Attribute|=value] Selects an element that is equal to the given string or prefixed with the string (followed by a hyphen "-");
- [Attribute~=value] Select an element with a space-delimited value that contains a given value;
- [AttrSel1] [AttrSel2] [Attrseln] is combined with a property selector into a composite property selector that satisfies multiple conditions. Reduce the range once per selection.
(5) Sub-element filter Selector
- : Nth-child (index/even/odd/equation) selects the index element or the odd-even element under each parent element (index starts at 1);
- : First-child selects the 1th child element of each parent element;
- : Last-child selects the last child element of each parent element;
- : Only-child If an element is the only child element in its parent element, it will be matched. If the parent element contains other elements, it will not be matched.
(6) Form object property Filter Selector
- : Enabled selects all available elements;
- :d isabled Select all the unavailable elements;
- : Checked Select all selected elements (Radio box, check box);
- : Selected selects all selected option elements (drop-down list).
- : input selects all the <input>, <textarea>, <select>, and <button> elements;
- : Text selects all single-line text boxes;
- :p Assword Select all the password boxes;
- : Radio selects all the radio boxes;
- : checkbox selects all the multi-marquee;
- : Submit to select all the Submit button boxes;
- : Image selects all the images buttons;
- : Reset selects all reset buttons;
- : button to select all buttons;
- : File selects all the upload fields;
- : Hidden selects all invisible elements.
Some considerations in selectors
- The selector contains special characters such as ".", "#", "(" or "]"
According to the standard of the world, the attribute value cannot contain these special characters, but in the actual project occasionally encountered in the expression contains "#" and "." such as special characters, if the normal way to deal with the error. The way to resolve such errors is to escape with escape characters.
- The space in the selector is also not to be ignored, and a single space or less space may result in very different results.
Chapter 3rd DOM manipulation in jquery
DOM Classification of Operations
in general, DOM operations are divided into 3 areas, Dom core (core), Html-dom, and Css-dom.
Dom core is not specific to JavaScript, and it can be used by any programming language that supports the DOM.
Methods such as getElementById (), getElementsByTagName (), getattribute (), and setattribute () in JavaScript are all part of the DOM core.
Getting some objects, properties can be implemented either with the DOM core or with Html-dom. In contrast, html-dom code is usually short, but it can only be used to work with Web documents.
Css-dom is a CSS-specific operation. In JavaScript, the main function of Css-dom technology is to get and set various properties of a style object. By changing the various properties of the style object, you can make the Web page appear in a variety of different effects.
JQuery the DOM in Operation
- Find nodes
You can use the jquery selector to find nodes on the document tree.
Once you have used the jquery selector to find the element you want, you can use the attr () method to get the values of its various properties.
- Create a Node
Using jquery to dynamically create HTML elements is simple, convenient, and flexible. Cases:
var $li _1 = $ ("<li title=" banana "> Banana </li>");
Note: (1) dynamically created new element nodes are not automatically added to the document, but instead need to be inserted into the document using other methods.
(2) When creating a single element, pay attention to closing the label and using the standard XHTML format.
For example, to create a <p> element, you can use $ ("<p/>") or $ ("<p></p>"), but do not use $ ("<p>") or uppercase $ ("<P/>").
- Inserting nodes
Append () appends content to each matching element;
AppendTo () Appends all matching elements to the specified element
In fact, using this method is reversed by the normal $ (A). Append (b) operation, that is, not appending B to a, but appending a to B.
Prepend () to each matched element within the predecessor content;
Prependto () to place all matching elements in front of the specified element;
After () inserts the content after each matching element;
InsertAfter () Inserts all matching elements behind the specified element.
In fact, using this method is reversed by the regular $ (a). After (b), instead of inserting b behind a, insert a into the back of B.
Before () inserts the content before each matching element;
InsertBefore () Inserts all matching elements in front of the specified element.
- Delete a node
Remove () method
When a node is removed with the Remove () method, all descendant nodes that the node contains are deleted at the same time. The return value of this method is a reference to the node that has been deleted, so you can use the elements later.
The Remove () method can also selectively delete elements by passing parameters.
Detach () method
Detach () and remove () also remove all matching elements from the DOM. Unlike remove (), all bound events, attached data, and so on are preserved.
Empty () method
Strictly speaking, the empty () method is not to delete a node, but to empty the node, which empties all the descendant nodes in the element.
- Replication nodes
You can use the Clone () method to copy nodes.
When a node is copied, the new element that is copied does not have any behavior. If you pass a parameter true in the Clone () method, it means to copy the element while copying the event that is bound in the element. Therefore, a copy of this element also has a copy function.
- Replace node
The function of the ReplaceWith () method is to replace all matching elements with the specified HTML or DOM elements.
Another method is ReplaceAll (), which is the same as the ReplaceWith () method, except that it reverses the replacewith () operation.
- Parcel nodes
Wrap () can be used if you want to wrap a node with other tags. This method is useful for inserting additional structured markup into a document, and it does not break the semantics of the original document.
The Wrap () method is to wrap all the elements in a separate package.
The Wrapall () method wraps all matching elements with an element. If there are other elements between multiple elements of the package, the other elements are placed behind the wrapping element.
The Wrapinner () method wraps the child content of each element, including the text node, with other structured markup.
- Property manipulation
In jquery, you use the attr () method to get and set the attributes of an element, and the Removeattr () method to delete an element's properties.
- Style actions
Get styles and set styles
Both the Get class and the set class can be done using the attr () method. Using the attr () method to set the class, if the original class exists, the original class will be replaced with the new class.
Append style
jquery provides a dedicated addclass () method to append styles.
Remove Style
To delete a value of class, you can use the Removeclass () method to complete the removal of all or the specified class from the matching element.
Delete multiple class names, which can be separated by a space.
When it has no parameters, it will delete all the values of class.
Toggle Style
The toggle () method mainly controls the repetitive switching of behavior. Such as:
$toggleBtn. Toggle (function () {
Display element
},function () {
Hide elements
})
In addition, jquery provides a Toggleclass () method to control the repetition of the switch on the style. If the class name exists, delete it and add it if the class name does not exist. Cases:
$ ("P"). Toggleclass ("another");
Determine if a style is included
Hasclass () can be used to determine if an element contains a class. Returns true if any, otherwise false is returned.
- Set and get HTML, text, and values
The HTML () method is similar to the innerHTML property in JavaScript, and can be used to read or set the HTML content of an element.
The HTML () method can be used for XHTML documents, but not for XML documents.
The text () method is similar to the InnerText property in JavaScript and can be used to read or set the text content of the pastoral element.
The Val () method is similar to the Value property in JavaScript and can be used to set and get the value of an element.
Whether the element is a text box, a drop-down list, or a radio box, it can return the value of an element.
If the element is multi-selected, returns an array containing the value you want to select.
- Traversing nodes
The children () method is used to obtain a collection of child elements of the matching element. Note that this method only considers child elements regardless of other descendant elements.
The next () method is used to obtain the sibling elements immediately following the matching element;
The Prev () method is used to get the sibling element immediately preceding the matching element;
The siblings () method is used to obtain all sibling elements before and after matching elements;
The closest () method is used to obtain the closest matching element.
First, check if the current element matches and return the element itself if it matches.
If a mismatch is found, the parent element is looked up, and the element that matches the selector is picked up.
If nothing is found, an empty jquery object is returned.
The parent () method is used to get each matching parented element in the collection
The parents () method is used to get each matching ancestor element in the collection
The closest () method starts with the element itself, matches the ancestor element step by step, and returns the first matching ancestor element.
- Css-dom operation
You can use the CSS () method directly to get the style attributes of an element, whether it is an external CSS import or directly stitched into an HTML element (inline).
You can also use the CSS () method directly to set a single style or multiple style attributes for an element.
Note: (1) If the value is a number, it will be automatically converted to a pixel value.
(2) in the CSS () method, if the attribute value has a "-" symbol, such as the font-size and Background-color attributes, if the value of these properties is set without the quotation marks, then the camel style is used.
If you enclose the quotation marks, it can be written as "fint-size" or "fontSize".
It is advisable to bring in quotation marks to develop good habits.
In jquery, there is another way to get the height of an element, which is high (). Its function is to obtain the current calculated height value (px) of the matching element.
The height () method can also be used to set the altitude of an element, and the default unit is PX if the value passed is a number. If you want to use a different unit (for example, EM), you must pass a string.
The difference between the two: the CSS () method gets the height value associated with the style settings, may get "auto", may also get "10px" such as a string, and the height () method gets a value of the element is the actual height of the page, regardless of the style settings, and without units.
There is also a width () method corresponding to the height () method, which can get the width value (px) of the matching element.
In addition, there are several commonly used methods for element positioning in Css-dom.
The offset () method is used to get the relative offset of the element in the current window, where the returned object contains two attributes, top and left, which are valid only for the visible element.
The function of the position () method is to get the relative offset of the element relative to the nearest position style property set to relative or absolute's grandfather node, where the returned object also includes two properties, top and left.
The ScrollTop () method and the ScrollLeft () method are used to obtain the distance from the top of the scrollbar of the element and the distance from the left.
Alternatively, you can specify a parameter for both methods, and the control element's scroll bar scrolls to the specified position.
jquery selector and DOM operations-"sharp jquery" (2nd edition) reading notes 1