Snoop jQuery-oriented JavaScript programmer



When jQuery appeared in January 2006 when, to my first impression is that this stuff very smart structure. Based on CSS selectors (CSS selectors) to get set up, its quite clever ideas (see getElementsBySelector). But the chain box fortifications (chaining stuff) look more like a gimmick, and overall seems, jQuery library provides the functionality and can not cover all the basic things. Therefore, I conclude, jQuery will flash in the pan.

Months, I came to understand their own wrong. Consideration from a technical craft, jQuery is very sharp. It uses simple way to encapsulate a large number of commonly used functions and provides sophisticated plug-in API, to meet the standard library other than the functional modules. jQuery uphold the core, is a collection of DOM elements (Yi Zhu: usually some subset of) - it is to set as a fundamental element to a high degree of abstraction out. The most important thing is to follow best practices of this abstract, jQuery and other JavaScript code that lets get along.

Many of the jQuery presentation are for junior designers and developers. Next, I would like to explain why jQuery will attract experienced developers.

Name space (Namespacing)

Write reusable, good JavaScript code, the key lies in the name of the active space to control. JavaScript has only a single, global name space (ie, window object), and many programmers (and some libraries) to whom wanton add all sorts of things. To understand the global variable is the devil! Smart developers will use similar technology component model, to try to reduce the number of global objects.

jQuery global name space only to introduce a tag: jQuery function / object. The rest are either the direct property jQuery (Yi Zhu: Original 'directy property' line typo, should be the 'direct property'), or call the jQuery function is the object returned by the method.

In the language of upgrading, jQuery provides many functions (function), but each functions are assigned to jQuery object attributes: jQuery.each, jQuery.extend, jQuery.grep, jQuery.map, jQuery.merge, and jQuery.trim . In this way, they will not conflict with other code.

The infamous $ function (The infamous $ function)

As I said, jQuery is the only global marking the introduction, is not necessarily so: $ tags as jQuery shortcut was introduced come. Fortunately, there is $'s no negative impact: If you need to revive the original $ (for example, before that your code uses Prototype), you can call jQuery.noConflict () to restore it.

If you only want to have $'s convenience and do not wish to use jQuery with other global $ function the same code conflict, the document proposed to follow the usual jQuery way:

(Function ($) (/ / in the function body, the $ can be used as a reference to jQuery / / is easy, right?)) (JQuery);

Everything attached to the $ mark practice gave its flashy I think jQuery. However, from the system to look at this design point of view, everything is very straightforward - though I often prefer to define their own code $ shortcut.

Select the element (Selecting some elements)

jQuery for each operation, are to select one or more DOM nodes (nodes) as a start. jQuery (have a real domain specific) selection syntax is very interesting, a combination of CSS 1, CSS 2, CSS 3 grammar section, a number of XPath syntax, and some specific extensions. I will not do in detail here, I only listed a few useful examples:

$ ('Div.panel')

Select all the class = "panel" of the div

$ ('P # intro')

Select all the id = "intro" paragraph

$ ('Div # content a: visible')

Select a id = "content" of all the visible link div

$ ('Input [@ name = email]')

Select all the name = "email" in the input field

$ ('Table.orders tr: odd')

Select a category called "orders" all the odd table rows

$ ('A [@ href ^ = "http://"]')

Select all (with http:// at the beginning of) external link

$ ('P [a]')

Select all contain one or more linked paragraphs

In the above example,: visible and: odd are jQuery to achieve the expansion, very special. The attribute selection using @ as a marker in a manner and XPath as superior to CSS 2.

selected all-inclusive set of jQuery syntax, somewhat similar to regular expressions, like to take a complete digestion is a period of time.

JQuery selection through operations, we can get some great "stuff" (beast). They are a collection that contains a DOM element, and as such an array, with length attribute; index can be accessed through the elements of the collection. In the Firebug console in interactive mode, the collection was shown as an array, this feature very useful. Collection is actually a jQuery object, the object is given a lot of ways (methods), used to query, modify, extend the collection element.

jQuery methods (methods), essentially can be divided into three types: one can manipulate the elements that meet the match; a can return the first match to the value of the object; a set can be changed is selected.

I will not list all of the methods (refer to visualjquery.com), but I use an example to do some shows. If your browser installed Firebug, you can interactively run the sample code: the first to use this bookmarklet (Yi Zhu [1]) jQuery library to load any page to the browser, then paste the sample code in the Firebug console .

$ ('Div # primary'). Width (300);

The id = "primary" in the div width set to 300px

$ ('P'). Css ('line-height', '1 .8 em ');

All paragraphs of the line-height set to 1.8em

$ ('Li: odd'). Css ((color: 'white', backgroundColor: 'black'));

Add items to list the interval of two CSS rules; attention css () function can use an object instead of the two strings as parameters

$ ('A [@ href ^ = "http:// "]'). addClass (' external '). Attr (' target ',' _blank ');

To all (beginning with http://) external link add "external" class, and then strategically add target = "_blank" attribute. This example uses the chain box (chaining), introduced later will do.

$ ('Blockquote'). Each (function (el) (alert ($ (this). Text ())));

Traversal of each page

And to show its text content (including HTML tags)

$ ('A'). Html ('Click here!');

With the insidious "Click here!" Instead of all the links on the page of text

The following example shows how to get the first match jQuery object to the value of:

var width = $ ('div'). width ();

Page width of the first div

var src = $ ('img'). attr ('src');

The first page a picture of the src attribute value

var color = $ ('h1'). css ('color');

First

Color pattern value

JQuery's methods in construction, contains a very pleasant symmetry: When the two parameters passed to the method or an object, the method can be used to perform set operations; if only one parameter passed to the method, you can let it run value operations (Yi Zhu: Readers can control the sample code above, feel). This symmetry of design through the jQuery system, make API easier to remember grammar.

This section concludes with examples, showing some of the selected element can be set to change the method. Most of these methods have improved the ease of retrieval DOM:

$ ('Div'). Not ('[@ id]')

Those who do not return div id attribute

$ ('H2'). Parent ()

Back to those who are

Direct parent node element

$ ('Blockquote'). Children ()

Return all

Sub-node elements

$ ('P'). Eq (4). Next ()

The page to find the fifth paragraph (Yi Zhu: Because elements of the collection index starts with 0), and then the tree node layer structure relationship, locate and return to this paragraph to the right of siblings element node

$ ('Input: text: first'). Parents ('form')

To find and return the first page type = "text" form input field where the node elements, parents () optional parameter is another selector

Chain box (Chaining)

jQuery jQuery development team often boast of the chain box concept (Yi Zhu [2]), even in the Web site home page to promote "jQuery will change the way you write JavaScript." I personally feel, do somewhat mislead the public, I would like to tell you, you can take jQuery long, but the method should be avoided lengthy chain of boxes (chains of methods).

In other words, chain box is sometimes the same as magic. In addition to the various operations using chain case will stick together DOM methods, you can use jQuery's end () method, www.devdao.com to achieve forward or backward within a specific range of elements you need. This concept is difficult to explain. In essence, each time you use (such as children () or filter ()) method to change the element set, you can use these methods after the end (), to re-locate your initial set of selected elements. On this point, Jesse Skinner in his Simplify Ajax development with jQuery (Yi Zhu [3]) tutorial gives an example:

$ ('Form # login') / / first, hide the form, those with 'optional' class. Find ('label.optional'). Hide (). End () / / second step, the table One of the password input field rendering a red border. find ('input: password'). css ('border', '1 px solid red '). end () / / The third step is to add the form submitted for processing. submit (function () (return confirm ('Are you sure you want to submit?');));

This example reads like a sentence pun. The whole process is, first select a form, then select some elements which make changes, and then back to the form, as it defines a submit () processing.

Sample cool, but if you are not used, you can not use it. I am very happy to plan with custom code variables.

Operation DOM (DOM Manipulation)

jQuery provides several excellent large-scale operation DOM methods. The first one is amazing: jQuery () function can insert HTML DOM element fragments (in fact, the function will pay attention to '<' "starts with the string parameter):

var div = $ ('

Some text

');

Once you create the good of the div, we can continue to add properties to its chain of boxes:

var div = $ ('

Some text

'). AddClass (' inserted '). Attr (' id ',' foo ');

Now add the body on the div:

div.appendTo (document.body)

Or use the selector to add the div in front of the known elements:

div.prependTo ('div # primary')

Processing events (Handling events)

Need any JavaScript library event handling capabilities, jQuery is no exception. Similar to the attr () and css () of the act, all related with the event handling methods also has a double purpose: one is to function as a parameter, assign the event handler; one is without parameters, can simulate the events are triggered (Yi Zhu: provided that the event has been defined, can refer to visualjquery.com> Events> click ()):

$ ('P'). Click (function () ($ (this). Css ('background-color', 'red');));

Increase the click event for all the paragraphs, when you click on them, the paragraphs will become a red background

$ ('P: first'). Click ()

Then in the first paragraph on the simulation click on the action, its background will turn red

A similar function also includes the mouseover, keyup, etc., corresponds to the browser normally supports those actions. Look at event handling in the 'this' keyword, which represents the triggering event of the element; $ (this) is an idiom, can represent this element of the application of various jQuery method.

There are two functions associated with the event should be careful that it:

$ ('A'). Hover (function () ($ (this). Css ('background-color', 'orange');}, function () ($ (this). Css (' background-color ', 'white');});

hover () to set the two functions corresponding to onmouseover and onmouseout events.

$ ('P'). One ('click', function () (alert ($ (this). Html ());));

one () to set the event is triggered after the first was removed. The above example will make all the paragraphs in the first clicked to display its text.

With the bind () and trigger () method, jQuery also can support custom event (click () methods of family simply convenient, support only limited events). Custom Event acceptable parameters, trigger () accept an array as a parameter, to do all kinds of processing operations:

$ (Document). Bind ('stuffHappened', function (event, msg) (alert ('stuff happened:' + msg );});$( document). Trigger ('stuffHappened', ['Hello!']) ;

Progressive coding (Unobtrusive scripting)

The title of this section is that I love. I always thought the best Web applications are often those who are disabled in the script, even after normal use of the procedure. Want to build such applications, the best way is to follow the progressive coding to let the page fully loaded, and then assigned to page elements to the event handler (for more information refer to progressive coding and Hijax).

jQuery coding strategy for this excellent support. First of all, on the whole, the node and select coincide jQuery core concept of progressive coding. Second, for the window.onload problem, jQuery provides a solution, this program draws on the results of Dean Edward made to "DOM is loaded," as the signal event that is cross-browser work. You can fully loaded in the browser DOM and run a function after the set, as follows:

$ (Document). Ready (function () (alert ('The DOM is ready !');});

You can even pass a function to the $ () to a more simple way to achieve the same effect:

$ (Function () (alert ('The DOM is ready !');});

jQuery and Ajax (jQuery and Ajax)

I know in the mainstream JavaScript libraries, jQuery has the best Ajax API. Simple Ajax calls such as:

$ ('Div # intro'). Load ('/ some / fragment.html');

Code to GET request method, from / some / fragment.html file for HTML fragments, and the fragment carrying the id = "intro" of the div in.

When I first saw this line of code, almost no impression on it. It looks very simple, but if you want to use jQuery to do more complex things like show the progress Ajax load, how should it? JQuery for you some of the events can be customized (ajaxStart, ajaxComplete, ajaxError, etc.) to achieve what you want the code. JQuery also offers a wide range of low-level API, to achieve more complex Ajax interactions:

jQuery.get ('/ some / script.php', ('name': 'Simon'), function (data) (alert ('The server said:' + data );}); / / GET method to pass / some / script.php? name = Simon obtain data jQuery.post ('/ some / script.php', ('name': 'Simon'), function (data) (alert ('The server said:' + data) ;)); / / way to POST to / some / script.php send requests jQuery.getJSON ('/ some.json', function (json) (alert ('JSON rocks:' + json.foo + '' + json . bar );}); / / from / some.json receive and parse the data, the data into JSON format jQuery.getScript ('/ script.js'); / / GET method to get / script.js script with eval () implementation

Plugins (Plugins)

On the function you can get the number of terms, jQuery library is actually quite small - so compact treatment of the code is only around 20KB, and even become more compressed with gzip small. Add additional functionality to the standard library, use a plug-in way to do, it can (and indeed can) to the existing jQuery instance object to add new methods. If you want to perform:

$ ('P'). BounceAroundTheScreenAndTurnGreen ();

jQuery's plugin mechanism provides documented type of mount method (documented hooks), can realize the above method to the jQuery,. The creation of such a simple form, has attracted a lot of plug-ins on their impressive; plugin directory now has over 100 plugins.