In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about the tool functions that must be known in jQuery. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
JQuery can also improve our efficiency in manipulating objects and arrays. And some common algorithms can be extended to jQuery tool functions to realize the reuse of script functions.
51CTO recommended topic: jQuery from beginner to proficiency
one。 What is a tool function?
Utility functions are functions defined on the jQuery object (that is, the variable "$"). These functions are utility functions. For example, the most commonly used trim () function in C#:
$.trim ("text")
There is no trim function in the original javascript that removes whitespace at the same time. Therefore, this kind of commonly used tool functions are collectively called "Utilities" functions. Corresponding to the official jQuery documents:
Http://docs.jquery.com/Utilities
"$" is actually a property of the "window" object, so the following sentences are equivalent:
two。 Tool function classification
Tool functions are mainly divided into the following categories:
◆ browser and feature testing
◆ array and object manipulation
◆ test operation
◆ string operation
◆ Url operation
Different from the explanation in the previous chapters, this article does not enumerate the list of functions. In the application, for example, if you want to manipulate a string, you can first find out whether a shortcut tool function has been provided in "API document / Utilities/ string Operation". If you do not consider your own development.
The following uses the tool functions commonly used under each category specific to the example.
three。 Browser and feature detection
The beauty of jQuery lies in its cross-browser nature, usually we no longer have to write different code for different browsers. But jQuery developers or plug-in developers have to handle browser differences on their own to provide users with cross-browser features.
JQuery provides the following properties for getting browser properties:
JQuery.support1.3 version added jQuery.browser repealed jQuery.browser repealed jQuery.browser repealed
Three attributes have been abolished in version 1.3 and will not be 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 respective features and bug of different browsers.
JQuery provides a range of properties, and you are free to add your own attributes. Many of these attributes are very low-level, so it's hard to say whether they can stay effective in the ever-changing development, but these are mainly used by plug-ins and kernel developers.
All of these supported property values are implemented by property detection, not by any browser. Here are some great resources to explain how these feature tests 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: if the page and browser are rendered with the W3C CSS cartridge model, it is equal to true. This value is usually false in the quirk mode of IE 6 and IE 7. Before document is ready, this value is null.
CssFloat: if cssFloat is used to access the value of float of CSS, true is returned. Currently, false is returned in IE, which uses styleFloat instead.
HrefNormalized: if the browser returns an intact result from getAttribute ("href"), it returns true. False is returned in IE because his URLs has been routinized.
HtmlSerialize: if the browser serializes links when inserting link elements through innerHTML, it returns true, and currently returns false in IE.
LeadingWhitespace: if the browser keeps leading whitespace characters when using innerHTML, it returns true, and currently returns false in IE 6-8.
NoCloneEvent: if the browser does not copy the element with the event handler when it clones, it returns true, and currently returns false in IE.
ObjectAll: true if executing getElementsByTagName ("*") on an element object returns all descendant elements, which is currently false in IE 7.
Opacity: if the browser can interpret the transparency style property properly, it returns true. Currently, it returns false in IE because it uses the alpha filter instead.
ScriptEval: whether or not the browser executes the script when inserting script code using the appendChild/createTextNode method, currently returns false,IE in IE to insert script code using the .text method to execute.
Style: true if getAttribute ("style") returns the inline style of the element. Currently, it is false in IE because it uses cssText instead.
Tbody: returns true if the browser allows the table element not to contain the tbody element. Currently, false is returned in IE, and it automatically inserts the missing tbody.
Explanation:
In view of the above many browser properties, this article only explains two features.
1. Box model boxModel
The following figure is a box model diagram in the W3C standard:
Suppose the following elements:
.boxModel {width:200px; height:50px; padding:10px; border:solid 5px # FF0000; background-color:#acacac;}
The display effect is as shown in the figure:
Set the width of the element to 200px in CSS, and here's an example of boxed mode.
W3C cartridge model:
The width and height of the element are the Context part of the box model diagram, excluding padding, border and margin parts.
At present, all browsers except IE only support W 3 C box model. In the W3C box model, the width of the area content including the red box in the example is 200+2*10+2*5=230px and the height is 50+2*10+2*5=80px.
IE cartridge model:
The width set includes padding,border. Actual content width content Width = width-padding-border
This model is used in IE5.5 and earlier versions. This cartridge mode will also be used in later versions of IE if browsers are run 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
The following is a comparison of the two box modes:
We can use the jQuery.support.boxModel property to find out whether the browser uses the W 3 C cartridge model. True means to use W3C boxModel.
two。 Floating style
When you set the float style of an element through a javascript script, IE is different from FireFox. IE uses style.styleFloat and FireFox uses style.cssFloat:
Div.style.styleFloat = "left"; / / IE div.stlye.cssFloat = "left"; / / FF
The jQuery.support.cssFloat property returns true to indicate that you can use cssFloat to set the float style. Return false in IE
Note that we can set the float style through the CSS () method, and the jQuery internal will automatically help us determine whether to use styleFloat or cssFloat:
$("# divResult"). Css ("float", "left"); / / compatible with IE and FF
four。 Array and object operations
To implement UI, we often operate on DOM objects or jQuery wrapper sets, but when implementing algorithms or business logic, we often operate on arrays and objects.
The following describes the most commonly used array and object-related tool functions.
1. Iteration
JQuery.each (object, callback)
Return value: Object
Description:
General routine method, which can be used to iterate through objects and arrays.
Unlike the $(). Each () method of the jQuery object, this method can be used to instantiate any object. The callback function has two parameters: * * is the index of the object's member or array, and the second is the corresponding variable or content. If you need to exit the each loop to make the callback function return false, other return values will be ignored.
Explanation:
For the jQuery wrapper set, we can use the each (callback) method to iterate over each element in the wrapper set. Callback is a function that accepts a parameter that represents the index of the current access object.
$("img") .each (function (I) {this.src = "test" + I + ".jpg";})
For arrays, we can use jQuery.each (object, callback) to traverse, which is equivalent to using for loops.
Note that the passed * parameters can be arrays or objects. If an array, traverse every object in the array. * parameters represent the index, the second parameter represents the value, and this represents the element currently traversed. You can terminate the iteration by returning false. For example, the following example terminates after traversing to the second element:
$.each (["a", "b", "c"], function (I, n) {alert ("Item #" + I + ":" + n); / / you can get the I value if (I > = 1) {return false;}}) ("# iterateArray") .click (function (event) {var array = $.each (["a", "b", "c"], function (I, n) {alert ("Item #" + I + ":" + n); / / * parameter I represents the index, and this represents the currently traversed object if (I > = 1) {return false;});})
If you pass an object, each property of the object is traversed, and even if the function returns false, it still traverses all the properties. * parameters represent the property key (attribute name, which is the type of obejct), the second parameter represents the value, and this represents the value of the current property:
$("# iterateObject") .click (function (event) {$.each ({name: "ziqiu.zhang", sex: "male", status: "single"}, function (I, n) {alert ("Item #" + i.toString () + ":" + n) / / * Parameter I represents the key (object) of the attribute, and this represents the attribute value if (I > = 1) {return false;}});})
Each will be the most frequently used function, especially note that although each iterates over every element or attribute, it does not change the value of the current element in the iterative function, that is, it cannot change the returned object. If you need to change each element in the array and return the result, use the jQuery.map (array, callback) function.
two。 Screening
JQuery.grep (array, callback, [invert])
Return value: Array
Description:
Use the filter function to filter array elements.
This function passes at least two parameters: the array to be filtered and the filter function. The filter function must return true to retain the element or false to delete the element.
Explanation:
The default invert is false, that is, the filter function returns true as the reserved element. If invert is set to true, the filter function returns true as deleted element.
The following example shows how to filter elements in an array whose index is less than 0:
$.grep ([0jue 1pl 2], function (NJI) {return n > 0;})
The returned result is [1pc2]
3. Conversion
JQuery.map (array, callback)
Return value: Array
Description:
Converts elements from one array to another.
The conversion function as an argument is called for each array element, and the conversion function is passed a representation of the converted element as the parameter. The conversion function can return the converted value, null (delete items in the array), or an array containing values, and extend to the original array.
Explanation:
In version 1.3.2, this function is almost the same as the each function (slightly different before). The only difference now is that the callback function can change the current element. Return null to delete the current element.
Here are a few examples:
Var arr = ["a", "b", "c", "d", "e"] $("div") .text (arr.join (",")); arr = jQuery.map (arr, function (n, I) {return (n.toUpperCase () + I);}); $("p") .text (arr.join (",")); arr = jQuery.map (arr, function (a) {return a + a;}) ("span") .text (arr.join (","))
4. Merge
Merging objects is a feature we often write, usually using bloated for loops. JQuery provides us with a lot of functional merge functions:
Name description example jQuery.extend ([deep], target, object1, [objectN]) extends an object with one or more other objects and returns the extended object.
If target is not specified, the jQuery namespace itself is extended. This helps plug-in authors add new methods to jQuery.
If the * * parameter is set to true, jQuery returns a deep copy and copies any object found recursively. Otherwise, the copy will share the structure with the original object.
Properties defined for will not be copied, while properties inherited from the object's prototype will be copied.
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 a class array object to an array object.
The class array object has a length property with a member index of 0 to length-1. In practice, this function will be used automatically in jQuery without the need for special conversion.
Convert a collection of DOM objects to an array:
Var arr = jQuery.makeArray (document.getElementsByTagName ("div")); jQuery.inArray (value, array) determines the position of * * parameters in the array, counting from 0 (returns-1 if not found). 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); / /-jQuery.merge (first, second) merges two arrays
The returned result modifies the contents of the * array-- the elements of the array are followed by the elements of the second array. To remove duplicates, use $.unique ()
Merge two arrays into * arrays:
Merge ([0rem 1pr 2], [2pr 3pr 4])
Results:
[0,1,2,2,3,4]
JQuery.unique (array) removes repeating elements from the array. You can only delete an array of DOM elements, not an array of strings or numbers. Delete duplicate div tags:
Unique (document.getElementsByTagName ("div"))
[,...]
Explanation:
The above function looks a little confusing. Let's see what we'll use in the future.
The first is jQuery.merge (first, second), which combines the two numbers. The following example shows how to use this function:
JQuery Utilities-jQuery.merge $(function () {$("# go") .click (function (event) {$("# divResult") .html (""); var first = [1,3,5] Append ("first: [" + first.join (",") + "]) .append ("); var second = [2,4,6]; $(" # divResult ") .append (" second: ["+ second.join (", ") +"]) .append (""); var result = $.merge (first, second) Append ("result: [" + result.join (",") + "]) .append ("); $(" # divResult ") .append (" first after merged: ["+ first.join (", ") +"] "); $(" # divResult ") .append (" second after merged: ["+ second.join (", ") +"] ") }); merge array
The result is shown in the figure:
Besides, just because we have jQuery, we can't forget our original javascript. Join and split functions are actually more commonly used than merge.
The merge function changes * merged arrays, which I wouldn't have done if I had designed it. Because the return value is already a merged array. This design makes the function ambiguous.
So many functions in the list are no longer explained one by one. Use it first and check first. Except for the function jQuery.extend, which has to be mentioned. The following is a brief summary to explain.
5. JQuery.extend
This function is most commonly used to deal with options when developing plug-ins.
Here is the code for the fancybox plug-in to get the options:
Settings = $.extend ({}, $.fn.fancybox.defaults, settings)
The above code target is an empty object. Take the default setting defaults as * objects and merge the user-passed setting setting into default. Some attributes on setting are subject to setting. If setting has no attributes passed in, the default value of default is used. The result of the merge is then copied to target and returned as a function return value.
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:
Settings = = {validate: true, limit: 5, name: "bar"}
Empty = = {validate: true, limit: 5, name: "bar"}
The target parameter passes an empty object because the value of target will be changed. For example:
Var defaults = {validate: false, limit: 5, name: "foo"}; var options = {validate: true, name: "bar"}; var settings = jQuery.extend (defaults, options)
The above code takes defaults as the target parameter, although the result of * settings is the same, but the value of defaults has been changed! The default value in the plug-in should be fixed! So please pay attention to the use of the target parameter when using.
Here are my complete examples and results:
JQuery Utilities-jQuery.extend $.toObjectString = function (obj) {var result = "{"; var counter = 0; $.each (obj, function (I, n) {if (counter > 0) {result + = "," } result + = i.toString () + ":" + n.toString (); counter++;}); result + = "}"; return result } $(function () {$("# go1") .click (function (event) {$("# divResult") .html (""); var empty = {} var defaults = {validate: false, limit: 5, name: "foo"} Var options = {validate: true, name: "bar"}; $("# divResult") .append ("empty:" + $.toObjectString (empty) + ") .append ("); $(" # divResult ") .append (" defaults: "+ $.toObjectString (defaults) +") .append ("") Append ("options:" + $.toObjectString (options) + ") .append ("); var settings = jQuery.extend (empty, defaults, options); $(" # divResult ") .append (" settings after extend: "+ $.toObjectString (settings) +") .append ("") $("# divResult") .append ("defaults after extend:" + $.toObjectString (defaults) + ") .append ("); $(" # divResult ") .append (" options after extend: "+ $.toObjectString (options) +") .append (");}) ("# go2") .click (function (event) {$("# divResult"). Html (""); var defaults = {validate: false, limit: 5, name: "foo"}; var options = {validate: true, name: "bar"} Append ("defaults:" + $.toObjectString (defaults) + ") .append ("); $(" # divResult ") .append (" options: "+ $.toObjectString (options) +") .append (""); var settings = jQuery.extend (defaults, options) Append ("settings after extend:" + $.toObjectString (settings) + ") .append ("); $(" # divResult ") .append (" defaults after extend: "+ $.toObjectString (defaults) +") .append (""); $("# divResult") .append ("options after extend:" + $.toObjectString (options) + ") .append (") ); jQuery.extend (empty, defaults, options) jQuery.extend (defaults, options)
Results:
five。 Test tool function
The test tool function is mainly used to determine whether the object is of a certain type, and all return Boolean values:
JQuery.isArray (obj)
JQuery.isFunction (obj)
And don't forget the isNaN and isFinite that come with javascript:
Var test = "123"; alert (isNaN (test)); alert (isFinite (test))
The isNaN function determines whether the parameter is non-numeric. If it is a number, return the false.isFinite function to check whether its argument is infinity. Returns false if the argument is NaN (non-numeric), or a positive or negative infinity number. Otherwise, return true.
six。 Operation tool function at character
Currently, there is only one string utility function in the core class library:
JQuery.trim (str)
Return value: string
Description: remove the spaces at the beginning and end of the string.
For example:
Remove the spaces at the beginning and end of the string:
$.trim ("hello, how are you?")
Results:
"hello, how are you?"
seven。 Url operation tool function
JQuery.param (obj)
Return value: string
Description:
Serialize an array of form elements or objects. Is the core method of .serialize ().
Arrays or jQuery objects are serialized according to name/value pairs, and ordinary objects are serialized according to key/value pairs
For example:
Var params = {width:1680, height:1050}; var str = jQuery.param (params); $("# results") .text (str)
Results:
Width=1680&height=1050
JQuery classifies it as Urls, because this method is usually used to pass the object as a urls parameter to the server when sending a GET request.
eight。 Extended tool function and jQuery wrapper set function
The extension tool function only needs to extend jQuery (that is, "$"). Usually people who develop tool functions or plug-ins want to use "$" when developing, but because "$" may conflict with other script libraries, we usually use the following syntax development tool functions:
(function ($) {$.myExtendMethod = function (o) {alert (0);}) (jQuery)
The "$" in the function body is guaranteed to represent the jQuery object.
Then the development in this way can not enjoy the convenience of intelligent perception. In general, we put the extension tool function and the extension jQuery wrapper set function in a separate file.
The following example shows how to add a custom jQuery tool method and jQuery wrapper set method:
With the line reference, we can continue to use jQuery script IntelliSense in this js file. The tool function extended by the jQuery.myExtendMethod method .jQuery. FN. MyExtendMethod method extends the jQuery wrapper function, which adds methods to the objects obtained using $(). Similarly, use XML annotations, such as
You can also add IntelliSense hints to custom methods. The XML comments in the script are the same as those in .NET. You can refer to my other article about XML comments in .NET: using XML comments in .NET (1)-- XML comment tag
nine。 Summary
JQuery provides many tool functions that can meet our needs in general. But for operations such as JSON formatting, we need to extend ourselves, and the existing extension component resources will improve our development efficiency. This series of Ajax chapters introduce a JSON serialized component jQuery.json. More components need to be mined in the work.
These are the necessary tool functions in jQuery that Xiaobian shares with you. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.