Home >Web Front-end >JS Tutorial >Learn jQuery tool functions from scratch
Learn jQuery from scratch (1) A ground-breaking introduction
Learn jQuery from scratch (2) Universal selector
From scratch Start learning jQuery (3) Managing jQuery packaging sets
Learning jQuery from scratch (4) Using jQuery to operate the attributes and styles of elements
Learning jQuery from scratch (5) Events and event objects
Learn jQuery from scratch (6) Ajax in jQuery
Learn jQuery from scratch (7) jQuery animation-let the page move!
Learn jQuery from scratch (8) Interlude: jQuery implementation plan
Learn jQuery from scratch (9) jQuery tool functions
Learn jQuery from scratch (10) Practice of jQueryUI common functions
Learn jQuery from scratch (11) Practical form validation and auto-complete prompt plug-in
This series of articles will take you Enter the wonderful world of jQuery, which contains many authors' specific usage experiences and solutions. Even if you know how to use jQuery, you can still find some secrets while reading.
We often use scripts to handle various business logics. The most common ones are the operations of arrays and objects. jQuery tool functions provide convenient conditions for us to operate objects and arrays.
Most people only use jQuery Use selectors to select objects, or implement page animation effects. When processing business logic, we often write many algorithms by ourselves. This article reminds you that jQuery can also improve the efficiency of our operations on objects and arrays. And some common algorithms can be extended to jQuery tool functions , realize the reuse of script functions.
Tool function refers to a function defined on the jQuery object (i.e. variable "$") . These functions are all tool functions. For example, the most commonly used trim() function in C#:
$.trim(" text ");
The original javascript does not provide a trim function that simultaneously removes leading and trailing spaces. Therefore, this type of function is commonly used The tool functions are collectively called "Utilities" functions. Corresponding to jQuery official documentation:
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 ");
Tool functions are mainly divided into the following categories:
Browser and feature detection
Array and object operations
Test operation
String operation
Url operation
Different from the explanation method in the previous chapters, this article does not enumerate the function list. In the application, for example, if you want to operate a string, you can first read from the "API document /Utilities/String Operation"Check to see if a shortcut utility function has been provided. If you have not considered developing it yourself.
The following examples use specific commonly used utility functions under each category.
The excellence of jQuery lies in its cross-browser features. Usually we don’t need to write different codes for different browsers. But if jQuery developers or plug-in developers have to handle browser differences themselves in order to provide users with cross-browser features.
jQuery provides the following properties for obtaining browser features:
jQuery.support |
New in version 1.3 | |
##jQuery .browser | Deprecated||
jQuery.browser.version | Deprecated ||
jQuery.boxModel | Deprecated
名称 | 说明 | 举例 |
jQuery.extend( [deep], target, object1, [objectN] ) |
用一个或多个其他对象来扩展一个对象,返回被扩展的对象。 如果不指定target,则给jQuery命名空间本身进行扩展。这有助于插件作者为jQuery增加新方法。 如果第一个参数设置为true,则jQuery返回一个深层次的副本,递归地复制找到的任何对象。否则的话,副本会与原对象共享结构。 为定义的属性将不会被复制,然而从对象的原型继承的属性将会被复制。 |
合并 settings 和 options,修改并返回 settings:
var settings = { validate: false, limit: 5, name: "foo" };
<br>var options = { validate: true, name: "bar" };
<br>jQuery.extend(settings, options);
结果: settings == { validate: true, limit: 5, name: "bar" }
|
jQuery.makeArray( obj ) |
将类数组对象转换为数组对象。 类数组对象有 length 属性,其成员索引为 0 至 length - 1。实际中此函数在 jQuery 中将自动使用而无需特意转换。 |
将DOM对象集合转换为数组:
var arr = jQuery.makeArray(document.getElementsByTagName("p"));
|
jQuery.inArray( value, array ) | 确定第一个参数在数组中的位置,从0开始计数(如果没有找到则返回 -1 )。 | 查看对应元素的位置:
var arr = [ 4, "Pete", 8, "John" ]; jQuery.inArray("John", arr); //3 jQuery.inArray(4, arr); //0 jQuery.inArray("David", arr); //-1 |
jQuery.merge( first, second ) |
合并两个数组 返回的结果会修改第一个数组的内容——第一个数组的元素后面跟着第二个数组的元素。要去除重复项,请使用$.unique() |
合并两个数组到第一个数组上:
$.merge( [0,1,2], [2,3,4] )
结果: [0,1,2,2,3,4] |
jQuery.unique( array ) | 删除数组中重复元素。只处理删除DOM元素数组,而不能处理字符串或者数字数组。 | 删除重复 p 标签:
$.unique(document.getElementsByTagName("p"));
[<p>, </p><p>, ...]</p> |
讲解:
上面的函数看着有些混乱. 看看我们以后会常用的.
首先是jQuery.merge( first, second ), 将两个数组合并. 下面这个示例说明如何使用此函数:
<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) { $("#pResult").html(""); var first = [1, 3, 5]; $("#pResult").append("<span>first:[" + first.join(",") + "]</span>").append("<br/>"); var second = [2, 4, 6]; $("#pResult").append("<span>second:[" + second.join(",") + "]</span>").append("<br/>"); var result = $.merge(first, second); $("#pResult").append("<span>result:[" + result.join(",") + "]</span>").append("<br/>"); $("#pResult").append("<span>first after merged:[" + first.join(",") + "]</span><br/>"); $("#pResult").append("<span>second after merged:[" + second.join(",") + "]</span><br/>"); }); }); </script></head><body> <button id="go"> 合并数组</button> <br /> <p id="pResult"> </p></body></html>
结果如图:
另外不能因为有了jQuery就忘记我们的原始javascript. 比merge更常用的其实是join和split函数.
merge函数会改变第一个合并的数组, 如果是我设计我就不会这么做. 因为返回值已经是合并后的数组了.如此设计让函数产生歧义.
列表中的那么多函数不再一一讲解. 先用先查. 除了 jQuery.extend 这个不得不提的函数. 下面单提一个小结讲解.
在开发插件的时候最常用此函数函数来处理options.
下面是fancybox插件获取options的代码:
settings = $.extend({}, $.fn.fancybox.defaults, settings);
上面的代码target是一个空对象, 将默认设置defaults作为第一个对象, 将用户传入的设置setting合并到default上, setting上有的属性以setting为准. setting没有传入的属性则使用default的默认值. 然后将合并的结果复制给target并作为函数返回值返回.
看一个完整的示例:
var empty = {}var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };var settings = jQuery.extend(empty, defaults, options);
结果:
settings == { validate: true, limit: 5, name: "bar" } empty == { validate: true, limit: 5, name: "bar" }
target参数要传递一个空对象是因为target的值最后将被改变.比如:
var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = jQuery.extend(defaults, options);
上面的代码将defaults作为target参数, 虽然最后settings的结果一样, 但是defaults的值被改变了! 而插件中的默认值应该都是固定! 所以使用时请注意target参数的用法.
下面是我的完整示例和结果:
<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) { 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) { $("#pResult").html(""); var empty = {} var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; $("#pResult").append("<span>empty:" + $.toObjectString(empty) + "</span>").append("<br/>"); $("#pResult").append("<span>defaults:" + $.toObjectString(defaults) + "</span>").append("<br/>"); $("#pResult").append("<span>options:" + $.toObjectString(options) + "</span>").append("<br/>"); var settings = jQuery.extend(empty, defaults, options); $("#pResult").append("<span>settings after extend:" + $.toObjectString(settings) + "</span>").append("<br/>"); $("#pResult").append("<span>defaults after extend:" + $.toObjectString(defaults) + "</span>").append("<br/>"); $("#pResult").append("<span>options after extend:" + $.toObjectString(options) + "</span>").append("<br/>"); }); $("#go2").click(function(event) { $("#pResult").html(""); var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; $("#pResult").append("<span>defaults:" + $.toObjectString(defaults) + "</span>").append("<br/>"); $("#pResult").append("<span>options:" + $.toObjectString(options) + "</span>").append("<br/>"); var settings = jQuery.extend(defaults, options); $("#pResult").append("<span>settings after extend:" + $.toObjectString(settings) + "</span>").append("<br/>"); $("#pResult").append("<span>defaults after extend:" + $.toObjectString(defaults) + "</span>").append("<br/>"); $("#pResult").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 /> <p id="pResult"> </p></body></html>
结果:
测试工具函数主要用于判断对象是否是某一种类型, 返回的都是Boolean值:
jQuery.isArray( obj )
jQuery.isFunction( obj )
同时别忘记了javascript中自带的isNaN和isFinite:
var test = "123"; alert(isNaN(test)); alert(isFinite(test));
isNaN函数判断参数是否是非数字. 如果是数字则返回false.
isFinite函数检查其参数是否是无穷大.如果参数是 NaN(非数字),或者是正、负无穷大的数,则返回 false.否则返回true.
目前核心类库中只有一个字符串工具函数:
jQuery.trim( str )
返回值: string
说明:去掉字符串起始和结尾的空格。
举例:
去掉字符串起始和结尾的空格:
$.trim(" hello, how are you? ");
结果:
"hello, how are you?"
jQuery.param( obj )
返回值:string
说明:
将表单元素数组或者对象序列化。是.serialize()的核心方法。
数组或jQuery对象会按照name/value对进行序列化,普通对象按照key/value对进行序列化
举例:
var params = { width:1680, height:1050 }; var str = jQuery.param(params); $("#results").text(str);
结果:
width=1680&height=1050
jQuery将其归为Urls分类, 因为此方法通常用于发送GET请求时将对象作为urls参数传递给服务端.
扩展工具函数只需要对jQuery(即"$")进行扩展. 通常开发工具函数或者插件的人希望在开发时使用"$", 但因为"$"有可能和其他脚本库冲突, 所以通常我们使用下面的语法开发工具函数:
(function($) { $.myExtendMethod = function(o) { alert(0); }; })(jQuery);
在函数体内的"$"能保证是代表jQuery对象.
然后使用这种方式开发不能享受到智能感知的便利. 一般我们将扩展工具函数和扩展jQuery包装集函数都放在一个单独的文件中.
下面这个示例演示如何添加自定义的jQuery工具方法和jQuery包装集方法:
/// <reference path="jquery-1.3.2-vsdoc2.js" />jQuery.myExtendMethod = function(o) { /// <summary> /// 扩展方法注释. /// </summary> /// <param name="o" type="String">参数提示文字</param> /// <returns type="string" >返回值提示文字</returns> alert(0); }; jQuery.fn.myExtendMethod = function(o) { /// <summary> /// 扩展方法注释. /// </summary> /// <param name="o" type="String">参数提示文字</param> /// <returns type="string" >返回值提示文字</returns> alert(0); };
Through the first line of 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 What is extended is the jQuery wrapper set function, which adds methods to objects obtained using $().
Similarly, you can use XML comments, such as
Using XML comments in .NET (1) -- Explanation of XML comment tags
jQuery provides many tool functions, which can meet our needs under normal circumstances. But for operations such as JSON formatting , we need to extend it ourselves. The existing various extended component resources will improve our development efficiency. This series of Ajax chapters introduces a JSON serialization component jQuery.json. More components are needed. Digging at work.
The above is the detailed content of Learn jQuery tool functions from scratch. For more information, please follow other related articles on the PHP Chinese website!