JQuery skills summary and jquery skills

Source: Internet
Author: User
Tags api manual

JQuery skills summary and jquery skills

I. Introduction

1.1 Overview

With the rapid development and dissemination of WEB2.0 and ajax ideas on the Internet, some excellent Js frameworks have emerged one after another, among them, Prototype, YUI, jQuery, mootools, Bindows, and JSVM frameworks in China are well-known, by applying these JS frameworks to our projects, programmers can be freed from complicated JS applications in design and writing, and focus on functional requirements rather than implementation details, this improves the project development speed.

JQuery is another excellent Javascript framework after prototype. It was created by John Resig in early 2006 and helps simplify JavaScript™And Ajax programming. Someone uses this analogy to compare prototype and jQuery: prototype is like Java, while jQuery is like ruby. it is a simple, fast, and flexible JavaScript framework that allows you to easily operate documents, process events, implement special effects, and add Ajax interactions to Web pages on your webpage.

It has the following features::

JQuery design will change the way you write JavaScript code, reduce the complexity of learning to use JavaScript to operate webpages, and improve the JS development efficiency of webpages, no matter for beginners of JS or senior experts, jQuery will be your first choice.

JQuery is suitable for designers, developers, and other good people. It is also suitable for commercial development. It can be said that jQuery is suitable for any JavaScript Application and can be used in different Web applications.

Official site: http://jquery.com/Chinese site: http://jquery.org.cn/

1.2 Purpose

By studying this document, you can have a simple understanding of jQuery, understand the differences between JQuery and other JS frameworks, and master the common syntax, usage skills, and precautions of jQuery.

Ii. Usage

Introduce the JQuery js file on the page that requires JQuery.
Example: <script type = "text/javascript" src = "js/jquery. js"> </script>
After the introduction, you can use the syntax provided by jQuery anywhere on the page.

Iii. Learning tutorials and references

See jQuery Chinese API manual and http://jquery.org.cn/visual/cn/index.xml
We recommend two good jquery Tutorials: jQuery's starting point tutorial and jQuery's simplified Ajax development.(Note: The above documents are included in [appendix)

Iv. Syntax summary and precautions


1. Reference of page elements

The $ () referenced element of jquery includes methods such as id, class, element name, element hierarchy, dom or xpath conditions, and the returned object is a jquery object (set object ), you cannot directly call methods defined by the dom.

2. Conversion between jQuery objects and dom objects

Only jquery objects can use methods defined by jquery. 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 through $.
For example, $ (document. getElementById ("msg") is a jquery object. You can use the jquery method.
Because the jquery object itself is a set. 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" cmd.html ();
$ ("# Msg") [0]. innerHTML;
$ ("# Msg"). eq (0) [0]. innerHTML;
$ ("# Msg"). get (0). innerHTML;

3. How to obtain a certain entry of the jQuery set

For the obtained element set, you can use the eq or get (n) method or index number to obtain one of the items (specified by the index). Note that the returned eq is a jquery object, get (n) and index return dom element objects. 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 <div> element. There are two methods:

$ ("Div" ).eq(2).html (); // call the jquery object Method
$ ("Div"). get (2). innerHTML; // call the dom method attribute

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 of msg. The page displays <B> new content </B>

$ ("# 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


The same blur, focus, select, and submit events can all have these 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:


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 ):

Alert ("a = 10, B = 20, max =" + $. max (10, 20) + ", 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(){alert(((this).html ())})
. Mouseover (function () {alert ('mouse over event ')})
. Each (function (I) {this. style. color = ['# f00',' #0f0 ',' # 00f'] [I]});

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 () {alert ("good")}) // added a click event for the element
$ ("P "). click (function (I) {this. style. color = ['# f00',' #0f0 ',' # 00f'] [I]}) // set different processing for three different p elements.

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 () {alert ("Load Success ")})
// After the page is loaded, the message "Load Success" is displayed. Unlike the onload event, onload requires that the page content be loaded (images, etc.), and ready is triggered when the html code of the page is downloaded. 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 () {alert ($ (this). 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) {alert ("Item #" + I + ":" + n );});

It is equivalent:
Var tempArr = [0, 1, 2];
For (var I = 0; I <tempArr. length; I ++ ){
Alert ("Item #" + I + ":" + tempArr [I]);

Json data can also be processed, such
$. Each ({name: "John", lang: "JS"}, function (I, n) {alert ("Name:" + I + ", Value: "+ n );});

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

Most of the time, we define the $ (id) method to obtain an element, or some 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 the jquery. noConflict (); Method in jQuery to assign control of the variable $ to the first library or the previously customized $ method to implement it. 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 ").
For example:

JQuery. noConflict ();
// Start using jQuery
JQuery ("div p"). hide ();
// Use $ () for other libraries ()
$ ("Content"). style. display = 'none ';



Jquery $ fn $ what is fx

$. Fn refers to the namespace of jquery. Adding Methods and attributes on fn will be effective for each jquery instance. For example, extend $. fn. abc () Then you can: $ ("# div "). abc (); extended by using the extend method. For details, see API. $. fx is the special effect of jquery. Display, slide, fade-in and fade-out, and animation are used. $. Fx. off can be used to close the animation and display the result directly. Extend and fn of jquery. extendjQuery provides two methods for development plug-ins: jQuery. fn. extend (object); jQuery. extend (object); jQuery. extend (object); to extend the jQuery class itself. add a new method for the class. JQuery. fn. extend (object); add a method to the jQuery object. What is fn. It is not difficult to see jQuery code. JQuery. fn = jQuery. prototype = {init: function (selector, context ){//.... //......}; jQuery. fn = jQuery. prototype. prototype is certainly not unfamiliar. Although javascript does not have a clear concept of a class, it is more convenient to use a class to understand it. JQuery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate a jQuery class instance. JQuery. extend (object); adding class methods to the jQuery class can be understood as adding static methods. For example: $. extend ({add: function (a, B) {return a + B ;}}); then add a "static method" for jQuery to add ", then you can use this method in the place where jQuery is introduced, $. add (3, 4); // return 7 jQuery. fn. extend (object); For jQuery. the extended prototype is to add a "member function" for the jQuery class ". JQuery class instances can use this "member function ". For example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert is displayed. You can do this: Java code $. fn. extend ({alertWhileClick: function () {$ (this ). click (function () {alert ($ (this ). val () ;};}}); $ ("# input1 "). alertWhileClick (); // on the page, <input id = "input1" type = "text"/>$ ("# input1") is a jQuery instance, when it calls the member method alertWhileClick, the extension is implemented. Each time it is clicked, the content in the current editing will pop up. In the real development process, of course, there will not be such a small plug-in. In fact, jQuery has provided a wide range of operations documents, events, CSS, Ajax, and effects methods, combined with these methods, you can develop more Niubility plug-ins. Differences between jquery (function () {}) and (function () {} (jQuery) 1. first jQuery (function () {}); all written as jQuery (docunemt ). ready (function () {}); meaning ...... remaining full text>

What are the differences between the add class method and the attr method of JQuery?

This cannot be the case,
1. addClass: The operation object is the style name, and the operation result is to add the specified style to the elements you operate:
For example, <div id = "AId"> </div>
$ ("# AId"). addClass ("class1") ;=> <div id = "AId" class = "class1"> </div>
2. the attr method adds certain attributes to the specified element.
$ ("# AId"). attr ("width", "200px") ;=> <div id = "AId" width = "200px"> </div>
Conclusion: addClass operates on styles, while attr operates on the attributes of elements. Of course, some attributes correspond to those in styles.

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.