Common jquery skills

Source: Internet
Author: User

1. Reference to page elements
using jquery $ () to reference elements, including IDs, classes, element names, hierarchical relationships of elements, Dom or XPath conditions, the returned object is a jquery object (set object) and cannot directly call the dom-defined method.

2. Conversion between jquery and DOM objects
only jquery objects can use jquery-defined methods. Pay attention to the differences between DOM objects and jquery objects. When calling methods, pay attention to DOM objects or jquery objects.
common DOM objects can be converted to jquery objects by $.
example: $ (document. getelementbyid ("MSG") is a jquery object. You can use the jquery method.
because jquery objects are a collection. Therefore, if a jquery object is to be converted to a DOM object, You must retrieve one of them. Generally, you can retrieve it through indexes.
For example: $ ("# MSG") [0], $ ("Div "). eq (1) [0], $ ("Div "). get () [1], $ ("TD") [5] are all DOM objects. You can use methods in Dom, but you cannot use jquery methods.
The following statements are correct:
$ ("# MSG" ).html ();
$ ("# MSG") [0]. innerhtml;
$ ("# MSG "). eq (0) [0]. innerhtml;
$ ("# MSG "). get (0 ). innerhtml;

3. How to obtain a jquery set
for the obtained element set, you can use the EQ or get (n) method or index number to obtain an item (specified by the index). Note that the returned EQ is a jquery object, while the get (N) and the index returns the DOM Element Object. Jquery objects can only use jquery methods, while DOM objects can only use Dom methods. For example, you need to obtain the content of the third

element. There are two methods:
$ ("Div" ).eq(2).html (); // call the jquery object method
$ ("Div "). get (2 ). innerhtml; // call DOM method attributes

4. Implement set and get for the same function
Many methods in jquery are like this, mainly including the following:
$ ("# MSG" ).html (); // return the HTML content of the element node whose ID is MSG.
$ ("# MSG" cmd.html ("<B> new content </B> ");
// Write "<B> new content </B>" as an HTML string to the element node content with the ID of MSG. The new content in bold is displayed on the page.

$ ("# MSG"). Text (); // return the text content of the element node whose ID is MSG.
$ ("# MSG"). Text ("<B> new content </B> ");
// Write "<B> new content </B>" as a common text string to the element node content with the ID MSG, <B> new content </B> in bold is displayed on the page.

$ ("# MSG"). Height (); // returns the height of the element whose ID is MSG.
$ ("# MSG"). Height ("300"); // set the height of the element whose ID is MSG to 300
$ ("# MSG"). Width (); // return the width of the element whose ID is msg
$ ("# MSG"). Width ("300"); // set the width of the element whose ID is MSG to 300

$ ("Input"). Val ("); // return the value of the input box of the form.
$ ("Input"). Val ("test"); // set the value of the form input box to test

$ ("# MSG"). Click (); // trigger the click event of an element whose ID is msg
$ ("# MSG"). Click (FN); // click an event to add a function for an element whose ID is msg
Similarly, blur, focus, select, and submit events can all have two call methods.

5. Set Processing
For the set content returned by jquery, we do not need to iterate through it and process each object separately. jquery has provided us with a very convenient way to process the set.
There are two forms:
$ ("P"). Each (function (I) {This. style. Color = ['# f00',' #0f0 ',' # 00f']})
// Set different font colors for P elements whose indexes are 0, 1 and 2 respectively.

$ ("TR"). Each (function (I) {This. style. backgroundcolor = ['# CCC', '# fff'] [I % 2]})
// Implement the Color Changing Effect of the row separation of the table

$ ("P" ).click(function(){.html ())})
// Adds a click event for each P element. Click a P element to bring up its content.

6. Expand the functions we need
$. Extend ({
Min: function (a, B) {return a <B? A: B ;},
MAX: function (a, B) {return A> B? A: B ;}
}); // Added the min and Max methods for jquery.
Use an extended method (called by "$. Method Name ):
+ ", Min =" + $. Min (10, 20 ));

7. method-based writing
The so-called continuous writing means that different methods can be called continuously for a jquery object.
For example:
$ ("P" ).click(function(){.html ())})
. Mouseover (function (){})
. Each (function (I) {This. style. Color = ['# f00',' #0f0 ',' # 00f']});

8. Style of operation elements
It mainly includes the following methods:
$ ("# MSG" ).css ("background"); // return the background color of the element.
$ ("# MSG" ).css ("background", "# CCC") // set the element background to Gray.
$ ("# MSG"). Height (300); $ ("# MSG"). Width ("200"); // set the width and height
$ ("# MSG" ).css ({color: "red", Background: "blue"}); // set the style as a name-Value Pair
$ ("# MSG"). addclass ("select"); // Add a class named select for the element
$ ("# MSG"). removeclass ("select"); // Delete the class whose element name is select
$ ("# MSG"). toggleclass ("select"); // Delete (ADD) the Select class if it exists (does not exist)

9. Complete event handling functions
Jquery already provides various event handling methods. Instead of Directly Writing events on HTML elements, we can directly add events to objects obtained through jquery.
For example:
$ ("# MSG"). Click (function () {}) // added a click event for the element
$ ("P"). Click (function (I) {This. style. Color = ['# f00',' #0f0 ',' # 00f']})
// Set different processing for three p-element click events
Several custom events in jquery:
(1) hover (fn1, FN2): a method that imitates a hover event (move the mouse over an object and remove it. When you move the cursor over a matching element, the specified first function is triggered. When you move the cursor out of this element, the specified second function is triggered.
// When you place the cursor over a row of the table, set the class to over and the class to out when you leave the table.
$ ("TR"). Hover (function (){
$ (This). addclass ("over ");
},
Function (){
$ (This). addclass ("out ");
});
(2) Ready (FN): binds a function to be executed when the Dom is loaded and can be queried and manipulated.
$ (Document). Ready (function (){})
// After the page is loaded, the message "load success" is displayed, which is equivalent to an onload event. Equivalent to $ (FN)
(3) Toggle (evenfn, oddfn): switches the function to be called each time you click. If a matching element is clicked, the specified first function is triggered. When the same element is clicked again, the specified second function is triggered. The subsequent clicks repeatedly call the two functions.
// Add or delete a class named selected every time you click it.
$ ("P"). Toggle (function (){
$ (This). addclass ("selected ");
}, Function (){
$ (This). removeclass ("selected ");
});
(4) trigger (eventtype): triggers an event on each matching element.
For example:
$ ("P"). Trigger ("click"); // triggers the click event of all P elements
(5) bind (eventtype, FN) and unbind (eventtype): bind and unbind events
Deletes a bound event from each matching element.
For example:
$ ("P"). BIND ("click", function () {. Text () ;}); // Add a click event for each P element
$ ("P"). Unbind (); // delete all events on all P elements
$ ("P"). Unbind ("click") // Delete the Click Event on all P elements

10. Some practical special effects
The toggle () and slidetoggle () methods provide the status switching function.
For example, the toggle () method includes the hide () and show () methods.
The slidetoggle () method includes the slidedown () and slideup methods.

11. Several useful jquery Methods
$. Browser. browser type: Check the browser type. Valid parameters: safari, opera, MSIE, and Mozilla. If IE: $. browser. isie is detected, true is returned for IE.
$. Each (OBJ, FN): A common iteration function. It can be used to iterate objects and arrays (instead of loops) in an approximate way ).
For example
$. Each ([0, 1, 2], function (I, n ){;});
It is equivalent:
VaR temparr = [0, 1, 2];
For (VAR I = 0; I <temparr. length; I ++ ){
;
}
JSON data can also be processed, such
$. Each ({name: "John", Lang: "JS"}, function (I, n ){;});
Result:
Name: name, value: John
Name: Lang, value: JS
$. Extend (target, prop1, propn): expands an object with one or more other objects and returns the extended object. This is an inheritance method implemented by jquery.
For example:
$. Extend (settings, options );
// Merge settings and options, and return the Merged Results to settings, which is equivalent to inheriting setting and saving the inherited results in setting.
VaR settings = $. Extend ({}, defaults, options );
// Merge ults and options, and return the merged result to setting without overwriting the default content.
There can be multiple parameters (merging multiple parameters and returning them)
$. Map (array, FN): array ing. Save the items in an array (after conversion) to another new array and return the new array.
For example:
VaR temparr = $. Map ([0, 1, 2], function (I) {return I + 4 ;});
Temparr content: [4, 5, 6]
VaR temparr = $. Map ([0, 1, 2], function (I) {return I> 0? I + 1: NULL ;});
Temparr content: [2, 3]
$. Merge (arr1, arr2): merges two arrays and deletes repeated items.
For example: $. Merge ([, 2], [, 4]) // return [, 4]
$. Trim (STR): removes spaces at both ends of a string.
For example: $. Trim ("Hello, how are you? "); // Return" Hello, how are you? "

12. Resolve conflicts between custom methods or other class libraries and jquery
in many cases, we define the $ (ID) method to obtain an element, or other JS class libraries such as prototype define the $ method, if these contents are put together at the same time, the variable method definition conflict will occur. jquery provides a dedicated method to solve this problem.
Use jquery in jquery. the noconflict (); Method transfers the control of variable $ to the first database that implements it or the previously customized $ method. When jquery is applied, you only need to replace all $ with jquery. For example, the original reference object method $ ("# MSG") is changed to jquery ("# MSG ").
example:
jquery. noconflict ();
// start using jquery
jquery (" Div P "). hide ();
// use $ () for other libraries ()
$ ("content "). style. display = 'none';

13. String replacement
Jquery can be used to replace a specific string in the text content:
VaR El = $ ('# id ');
El.html(el.html (). Replace (/word/ig ,""));

14. jquery (HTML, [ownerdocument])

Dynamically create DOM elements encapsulated by jquery Objects Based on the provided original HTML Tag string. You can pass a handwritten HTML string, a string created by some template engines or plug-ins, or a string loaded through Ajax. However, there are limits when you create an input element. For more information, see the second example.

Of course, this string can contain a slash (such as an image address) and a backslash. When creating a single element, use the closed tag or XHTML format. For example, to create a span, you can use $ ("<SPAN/>") or $ ("<span> </span> "), but $ ("<span>") is not recommended "). In jquery, this syntax is equivalent to $ (document. createelement ("span ")).

Parameters:

HTML (string): HTML Tag string used to dynamically create DOM elements

Ownerdocument (document): (optional) document where the DOM element is created

Example:

Dynamically create a div element (and all its content) and append it to the body element. In this function, an element is created temporarily and the innerhtml attribute of this element is set to a given tag string to convert the tag to the DOM element. Therefore, this function has both flexibility and limitations.

JqueryCode:

$ ("<Div> <p> Hello </P> </div>"). appendto ("body ");

To create a <input> element, you must set the type attribute at the same time. Because Microsoft requires that the type of the <input> element can be written only once.

Jquery code:

// It is invalid in IE:
$ ("<Input>"). ATTR ("type", "checkbox ");
// Valid in IE:
$ ("<Input type = 'checkbox'> ");

15. jquery (callback)

$ (Document). Ready. Allows you to bind a function that is executed after the DOM file is loaded. This function serves as $ (document ). the same as ready (), except that when using this function, you need to wrap all the $ () operators on the page that need to be executed during Dom loading. Technically, this function is connectable-but there are not many cases of actually linking in this way.

You can use any number of $ (document). Ready events on a page.

Parameters:

Callback (function): the function to be executed after the Dom is loaded.

Example:

After the Dom is loaded, execute the function.

Jquery code:

$ (Function (){
// The document is ready
});

Use the abbreviation $ (document). Ready (), while the internal jquery code still uses $ as the alias, regardless of the global $.

Jquery code:

Jquery (function ($ ){
// You can continue to use $ as an alias here...
});

 

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.