I. Summary
This series of articles will take you into the wonderful world of jquery, with many authors ' specific experiences and solutions, even if you can use jquery to find some cheats in your reading.
We often use scripting to handle a variety of business logic, the most common being the operations of arrays and objects. The jquery tool function provides a convenient condition for us to manipulate objects and arrays.
Two. Foreword
Most people simply use the jquery selector to select objects, or to achieve a page animation effect. You often write many of your own algorithms when dealing with business logic. This article reminds you that jquery can also improve the efficiency of our objects and arrays. Some common algorithms can be extended to jquery tool functions to realize the reuse of script functions.
Three. What is a tool function
A tool function is a function defined on a jquery object (that is, the variable "$"). These functions are tool class functions, such as the most commonly used trim () function in C #:
$.trim ("text ");
There is no trim function in the original JavaScript that removes both before and after spaces. So this kind of commonly used tool function is called "Utilities" function. Corresponding to the jquery Official document:
Http://docs.jquery.com/Utilities
"$" is actually a property of the "Window" object, so the following sentences are equivalent:
$.trim ("text ");
Window.$.trim ("text"); Window.jquery ("text"); Jquery.trim ("text");
Four. Tool function classification
Tool functions are mainly divided into the following categories:
- browser and feature detection
- array and object manipulation
- Test Actions
- string Manipulation
- URL Action
Different from the previous chapters, this article does not enumerate the list of functions. In applications, such as encountering a string to manipulate, you can first find out whether a quick tool function has been provided from the API document/utilities/string Operation . If no longer consider yourself developing.
The following is a common tool function that is used in each category of the instance specific.
Five. browser and feature detection
The best of jquery is its cross-browser features, and usually we don't have to write different code for different browsers. But if it's a jquery developer or plug-in developer, it's up to you to handle browser differences to provide users with cross-browser features.
jquery provides the following properties for obtaining browser attributes:
Jquery.support |
Version 1.3 new |
Jquery.browser |
has been abolished |
JQuery.browser.version |
has been abolished |
Jquery.boxmodel |
has been abolished |
Three attributes have been abolished in version 1.3 and are not explained here. Let's focus on the jquery.support function.
Jquery.support
return Value: Object
Description
JQuery 1.3 is new. A set of properties that show the characteristics and bugs of different browsers.
jquery provides a range of attributes, and you can also freely add your own attributes. Many of these properties are low-level, so it's hard to say whether they can be kept valid for ever-changing developments, but these are mainly for plug-ins and kernel developers.
All of these supported property values are implemented through attribute detection, rather than any browser detection. Here are some great resources to explain how these feature detections work:
- Http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
- http://yura.thinkweb2.com/cft/
- Http://www.jibbering.com/faq/faq_notes/not_browser_detect.html
Jquery.support mainly includes the following tests:
Boxmodel: This is true if the page and browser are rendered with the Web-browsers CSS box model. This value is usually false in the quirks mode of IE 6 and IE 7. This value is null until the document is ready.
cssfloat: Returns True if you use Cssfloat to access the values of the float of the CSS. Currently in IE will return false, he replaced with stylefloat.
hrefnormalized: Returns True if the browser returns an intact result from getattribute ("href"). Returns false in IE because his URLs are already conventionally made.
htmlserialize: If the browser serializes the link elements by innerhtml them, returns True, and the current IE returns FALSE.
Leadingwhitespace: Returns True if the browser retains leading white-space characters while using innerHTML, and now returns false in IE 6-8.
nocloneevent: If the browser does not replicate with the event handler when cloning elements, returns true and is currently returning false in IE.
Objectall: True if getElementsByTagName ("*") on an Element object returns all descendant elements, and is currently false in IE 7.
opacity: If the browser can properly interpret the transparency style attribute, returns True and is currently returning false in IE because he replaces it with an alpha filter.
scripteval: When inserting script code using the Appendchild/createtextnode method, the browser executes the script, and now returns False,ie in IE using the. Text method to insert the script code to execute.
style: True if GetAttribute ("style") returns the inline style of the element. The current IE is false because he replaces it with Csstext.
tbody: Returns True if the browser allows the table element to contain no tbody elements. Currently in IE will return false, he will automatically insert the missing tbody.
Explain:
For the numerous browser attribute attributes above, this article only explains two features.
1. Box-type model Boxmodel
The following figure is a box model diagram in the standard of the consortium:
Suppose the following elements:
<Type= "Text/css"</style<IDclass= "Boxmodel">
Display effect as shown in figure:
To set the element width to 200px in the CSS, take this element as an example to explain the box mode.
The box model of the Consortium:
The width and height of the element are the context portion of the box model diagram, excluding the padding, border, and margin sections.
At present, except IE all browsers support only the web-only box model . In the 200+2*10+2*5=230px model, the area with the red box in the example has a width of 50+2*10+2*5=80px and a height of the content.
IE-Box Model:
The width of the setting includes Padding,border. Actual content width = Width-padding–border
In IE5.5 and earlier versions, this model was used. In the higher IE version, this cartridge mode is also used if the browser is running in weird mode for some reason. So you need to declare the correct DOCTYPE on the page. For DOCTYPE please refer to this article:
Http://www.cnblogs.com/zhangziqiu/archive/2009/01/15/doctype.html
Here is a comparison of the two box modes:
We can use the JQuery.support.boxModel property to get whether the browser uses the web-capture box model. True indicates the use of the Boxmodel.
2. Floating style
When you set the float style of an element through JavaScript script, ie and Firefox are different, IE uses style.stylefloat, Firefox uses style.cssfloat:
"Left"; Ff
The JQuery.support.cssFloat property returns True to indicate that the float style can be set using Cssfloat. return false in IE;
Note that we can set the float style through the CSS () method, and jquery will automatically help us determine whether to use Stylefloat or cssfloat:
$ ("#divResult"). CSS ("float","left");//compatible with IE and FF
Six. Array and object manipulation
Implementing the UI we often manipulate DOM objects or jquery wrapper sets, but implementing algorithms or business logic often operates on arrays and objects.
The most commonly used array and object-related tool functions are explained below.
1. Iteration
Jquery.each (object, callback)
return Value: Object
Description
A universal example method, which can be used for example objects and arrays.
Unlike the $ (). each () method of the JQuery object, this method can be used to sample any object. The callback function has two parameters: the first is the index of the member or array of the object, and the second is the corresponding variable or content. If you need to exit each loop so that the callback function returns false, the other return values are ignored.
Explain:
For jquery wrapper sets we can use each (callback) method to iterate through each element of the wrapper set. Callback is a function that takes a parameter representing the index of the current Access object.
$ ("img"). each (". jpg";});
For arrays we can use Jquery.each (object, callback) to traverse, which is equivalent to using a for loop.
Note that the first argument passed in can be either an array or an object. If the array, iterate through each object in the array. The first parameter represents the index, and the second parameter represents the value, this represents the currently traversed element, and can terminate the iteration by returning false, for example, after traversing to the second element, the following example terminates:
$.each ([function (i, N) {alert (":" + N); False } });
$ ( "#iterateArray"). Click (function ( event) {var array = $.each ([ "a", "B", "C"], function (i, N) {alert ( "Item #" + i + ":" + N); //the first parameter I represents an index, this represents the currently traversed object if (I >= 1) {return FALSE; } }); });
If you pass an object, you traverse each property of the object, and even if the function returns False, the first parameter represents the property key (the property name, the obejct type), and the second parameter represents the value, which represents the value of the current property:
$ ( "#iterateObject"). Click (function ( event) {$.each ({name: "male", Status: "single"}, function (i, N) {alert ( "Item #" + i.tostring () + ":" + N); //the first parameter I represents the property's key (object), this represents the property value if (I >= 1) {return Span class= "KWRD" >FALSE; } }); });
Each will be the function we use most often, special note each, although iterating over each element or attribute, does not change the value of the current element in the iteration function, which means that the returned object cannot be changed. If you need to change each element of the array and return the result, use the Jquery.map (Array, callback) function.
2. Screening
Jquery.grep (Array, callback, [invert])
return value: Array
Description
Filter the array elements using the filter function.
This function passes at least two parameters: the array to be filtered and the filter function. The filter function must return true to preserve the element or false to delete the element.
Explain:
The default invert is false, that is, the filter function returns true as a reserved element. If the set invert is true, the filter function returns true to delete the element.
The following example shows how to filter an element with an index less than 0 in the array:
function (n,i) {return
n > 0;});
The result returned is [1,2]
3. Conversion
Jquery.map (Array, callback)
return Value: Array
Description
Converts an element in an array to another array.
The conversion function as a parameter is invoked for each array element, and the transformation function is passed a parameter that represents the converted element. A conversion function can return a converted value, null (delete an item from an array), or an array containing values, and extend to the original array.
Explain:
This function is almost the same as each function in the 1.3.2 version (slightly different before), and the only difference now is that the callback function can change the current element. Returns null deletes the current element.
Here are a few examples:
"E"] $ ("div"). Text (Arr.join (return(n.touppercase () + i);}), $ ("P"). Text (Arr.join (returnA + A;}); $ ( "span"). Text (Arr.join (","));
4. The merger
A merged object is a feature that we often write, usually using a bloated for loop. jquery provides us with a number of functions for merging functions:
Name |
Description |
Example |
Jquery.extend ([deep], Target, Object1, [objectn]) |
Extends an object with one or more other objects, returning the object being extended. If target is not specified, the jquery namespace itself is extended. This helps the plugin author add new methods for jquery. If the first argument is set to True, jquery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object. Properties that are defined will not be replicated, but properties inherited from the object's prototype will be replicated. |
Merge settings and options, modify and return settings:
var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options);
Results:
settings == { validate: true, limit: 5, name: "bar" }
|
Jquery.makearray (obj) |
Converts an array object of a class to a group object. The class array object has a length property and its member index is 0 to length-1. In practice, this function is automatically used in JQuery without deliberately converting it. |
To convert a collection of Dom objects to an array:
var arr = jQuery.makeArray(document.getElementsByTagName("div")); |
Jquery.inarray (value, array) |
Determines the position of the first parameter in the array, counting from 0 (if not found, returns-1). |
To view the location of the corresponding element:
var arr = [ 4, "Pete", 8, "John" ];
jQuery.inArray("John", arr); //3
jQuery.inArray(4, arr); //0
jQuery.inArray("David", arr); //-1
|
Jquery.merge (the second) |
Merging two arrays The returned result modifies the contents of the first array-the elements of the first array followed by the elements of the second array. To remove duplicates, use the $.unique () |
Merges two arrays onto the first array:
$.merge( [0,1,2], [2,3,4] )
Results:
[0,1,2,2,3,4]
|
Jquery.unique (Array) |
Deletes a repeating element in an array. Handles only the delete DOM element array, not the string or numeric array. |
To delete a repeating div tag:
$.unique(document.getElementsByTagName("div"));
[<div>, <div>, ...]
|
Explain:
The above function looks a bit messy. Let's see what we'll use later.
The first is jquery.merge, a combination of two numbers and a second. The following example shows how to use this function:
<Html xmlns= "Http://www.w3.org/1999/xhtml"> <Head> <Title>JQuery Utilities-jquery.merge</Title> <Script Src=".. /scripts/jquery-1.3.2-vsdoc2.js " Type= "Text/javascript"></Script><script type="Text/javascript"> $ (function() { $("#go"). Click (function(Event) { $("#divResult"). HTML ("");Var"A" [1, 3, 5]; $("#divResult"). Append ("<span>first:["+ First.join (",") +"]</span>"). Append ("<br/>");VarSecond = [2, 4, 6]; $("#divResult"). Append ("<span>second:["+ Second.join (",") +"]</span>"). Append ("<br/>");Varresult = $.merge (A, second); $("#divResult"). Append ("<span>result:["+ Result.join (",") +"]</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>first after merged:["+ First.join (",") +"]</span><br/>"); $("#divResult"). Append ("<span>second after merged:["+ Second.join (",") +"]</span><br/>"); }); });</Script> </head> <body> button id= "Go" > merge arrays </button> br /> <div = "Divresult" > > </body> < /html>
The result is as shown in figure:
In addition, you can't forget our original JavaScript because you have jquery. More commonly used than merge is the join and split functions.
The merge function will change the first merged array, and I wouldn't have done it if I had designed it. Because the return value is already a merged array. This design causes ambiguity in the function.
So many functions in the list are no longer explained in one by one. First Use first check. In addition to Jquery.extend the function that has to be mentioned. Here is a brief summary of the explanation.
5. Jquery.extend
This function function is most commonly used to handle options when developing plug-ins.
Here is the code for the FancyBox plug-in to get options:
Settings = $.extend ({}, $.fn.fancybox.defaults, settings);
The above code target is an empty object, defaults the default setting as the first object, merging the settings passed in by the user setting to default, and setting the properties on the setting. Setting no properties passed in, default defaults are used. The merged results are then copied to target and returned as function return values.
Look at a complete example:
var empty = {} var defaults = {validate: false, Limit:5, Name: " foo "}; var options = {validate: true, Name: "bar"}; var settings = Jquery.extend (empty, defaults, options);
Results:
"Bar"}
The target parameter passes an empty object because the value of target is eventually changed. For example:
"Bar"}; var settings = jquery.extend (defaults, options);
The above code takes defaults as the target parameter, although the result of the last settings is the same, but the value of the defaults is changed! and the default values in the plugin should all be fixed! Note the use of the target parameter when using.
Here are my complete examples and results:
<Html xmlns= "Http://www.w3.org/1999/xhtml"> <Head> <Title>JQuery Utilities-jquery.extend</Title> <Script Src=".. /scripts/jquery-1.3.2-vsdoc2.js " Type= "Text/javascript"></Script><script type="Text/javascript"> $.toobjectstring =function(obj) {Varresult ="{";VarCounter = 0; $.each (obj,function(I, N) {If(Counter > 0) {result = =","; Result + = i.ToString () +":"+ n.tostring (); counter++; }); result = ="}";ReturnResult } $(function() { $("#go1"). Click (function(Event) { $("#divResult"). HTML ("");Varempty = {}VarDefaults = {validate:False, Limit:5, Name:"Foo"};VarOptions = {validate:True, Name:"Bar"}; $("#divResult"). Append ("<span>empty:"+ $.toobjectstring (empty) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>defaults:"+ $.toobjectstring (defaults) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>options:"+ $.toobjectstring (options) +"</span>"). Append ("<br/>");VarSettings = Jquery.extend (empty, defaults, options); $("#divResult"). Append ("<span>settings after Extend:"+ $.toobjectstring (Settings) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>defaults after Extend:"+ $.toobjectstring (defaults) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>options after Extend:"+ $.toobjectstring (options) +"</span>"). Append ("<br/>"); }); $("#go2"). Click (function(Event) { $("#divResult"). HTML ("");VarDefaults = {validate:False, Limit:5, Name:"Foo"};VarOptions = {validate:True, Name:"Bar"}; $("#divResult"). Append ("<span>defaults:"+ $.toobjectstring (defaults) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>options:"+ $.toobjectstring (options) +"</span>"). Append ("<br/>");VarSettings = Jquery.extend (defaults, options); $("#divResult"). Append ("<span>settings after Extend:"+ $.toobjectstring (Settings) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>defaults after Extend:"+ $.toobjectstring (defaults) +"</span>"). Append ("<br/>"); $("#divResult"). Append ("<span>options after Extend:"+ $.toobjectstring (options) +"</span>"). Append ("<br/>"); }); });</Script> </Head> <Body> <button Id= "Go1" Style= "height:40px;width:400px;">Jquery.extend (Empty, defaults, options)</button> button id= "Go2" style = "height:40px;width:400px;" > jquery.extend (defaults, options) </button> <br /> div id= "Divresult" > </div> body> >
Results:
Seven. Test tool functions
The test tool function is primarily used to determine whether an object is a certain type and returns a Boolean value:
Jquery.isarray (obj)
Jquery.isfunction (obj)
Also, don't forget the isNaN and isfinite that come with javascript:
"123"; Alert (isNaN (test)); Alert (isfinite (test));
The isNaN function determines whether the parameter is non-numeric. Returns False if it is a number.
The Isfinite function checks whether its arguments are infinite. Returns False if the argument is NaN (non-numeric) or positive or negative infinity. Otherwise, returns True.
Eight. Operation tool function at character
There is only one string tool function in the Core class library:
Jquery.trim (str)
return value: string
Description: Removes the space at the beginning and end of the string.
Example:
Remove the space at the beginning and end of the string:
$.trim ("Hello, how are you?");
Results:
"Hello, how are?"
Nine. URL Manipulation tool function
Jquery.param (obj)
return value:string
Description
Serializes a group of table cell primes or objects. Is the core method of. Serialize ().
Arrays or jquery objects are serialized according to Name/value, and ordinary objects are serialized according to Key/value
Example:
var str = Jquery.param (params); $ ("#results"). Text (str);
Results:
width=1680&height=1050
jquery classifies it as a URL, because this method is typically used to pass the object as a URL parameter to the server when sending a GET request.
10. Extended tool functions and jquery wrapper set functions
Extension tool functions only need to extend the jquery (that is, "$"). People who typically develop tool functions or plug-ins want to use "$" at development time, but because "$" is likely to conflict with other script libraries, we typically use the following syntax to develop tool functions:
(function ($)
{
function (o) {alert (0);};}) (jQuery);
The "$" in the body of the function is guaranteed to represent the jquery object.
Then use this approach to develop the convenience of not enjoying IntelliSense. In general, we put extension tool functions and extended jquery wrapper set functions in a separate file.
The following example shows how to add a custom jquery tool method and a jquery wrapper set method:
///<reference path= "Jquery-1.3.2-vsdoc2.js"/> Jquery.myextendmethod = function (o) {///<summary> /// extension method annotations. ///</summary> ///<param "O" name= "String" > Parameter hint text type= > ///<returns type= "string" > Return value Hint text </returns> alert (0);}; JQuery.fn.myExtendMethod = function (o) {///<summary> ///</summary> ///<param "O" name= "String" > Parameter hint text type= > ///<returns type= "string" > Return value Hint text </returns> alert (0);}
With the first line of reference, we can continue to use jquery script IntelliSense in this JS file.
A tool function that jquery.myextendmethod the method extension.
The JQuery.fn.myExtendMethod method extends the jquery wrapper set function, which adds a method to the object that is obtained by using $ ().
Similarly, using XML annotations, such as <summary>, can also add IntelliSense hints for custom methods. XML annotations in the script are the same as in. Net. NET can refer to my other article in the XML annotation:
Use. XML annotation in net (i)--Explanation of XML annotation label
11. Summary
jquery provides a number of tool functions that, in general, can meet our needs. But for operations like JSON formatting, we need to expand our own, and the various extensions that are available will improve our development efficiency, and this series of Ajax chapters describes a JSON-serialized component Jquery.json. More components need to be mined at work.
Author: Zhang Zixiu
Source: http://www.cnblogs.com/zhangziqiu/