Table of Contents
Previous words
Element related
Data related
Type detection
Array related
其他
Home Web Front-end JS Tutorial jQuery common tool methods

jQuery common tool methods

Jun 26, 2017 pm 02:32 PM
jquery Common tool method

Previous words

jQuery provides some tool methods that have nothing to do with elements. You can use these methods directly without selecting the element. If you understand the inheritance principle of native JavaScript, you can understand the essence of tool methods. It is a method defined on the jQuery constructor, that is, jQuery.method(), so it can be used directly. Those methods for operating elements are methods defined on the prototype object of the constructor, that is, jQuery.prototype.method(), so an instance must be generated (that is, the element is selected) before use. Just think of tool methods as methods that can be used directly like JavaScript native functions. The following will introduce in detail the common tool methods of jQuery

【each()】

It is a general iteration function that can be used to seamlessly iterate over objects and arrays. Arrays and array-like objects iterate through a length property (such as a function's argument object) with numeric indices, from 0 to length - 1. Other objects are iterated through their property names

1

jQuery.each( collection, callback(indexInArray, valueOfElement) )

Copy after login

The jQuery.each() function is different from jQuery(selector).each(), which is specifically used to iterate over a jQuery object. The jQuery.each() function can be used to iterate over any collection, whether it is a "name/value" object (JavaScript object) or an array. In the case of iterating an array, the callback function is passed one array index and the corresponding array value as arguments each time. (The value can also be obtained by accessing the this keyword, but JavaScript will always treat the this value as an Object, even if it is a simple string or numeric value.) The method returns its first argument, which is the object to be iterated over

1

2

$.each( ['a','b','c'], function(index,value){//Index #0: a//Index #1: b//Index #2: cconsole.log( "Index #" + index + ": " + value );

});

Copy after login

1

2

$.each( { name: "John", lang: "JS" }, function(index,value){//Index #name: John//Index #lang: JSconsole.log( "Index #" + index + ": " + value );

});

Copy after login

【contains()】

Check that a DOM element is a descendant of another DOM element

1

jQuery.contains( container, contained )

Copy after login

1

$.contains( document.documentElement, document.body ); // true

Copy after login

【extend()】

Merge the contents of two or more objects into the first object

1

2

3

4

5

jQuery.extend( target [, object1 ] [, objectN ] )

 

target: Object 一个对象,如果附加的对象被传递给这个方法将那么它将接收新的属性,如果它是唯一的参数将扩展jQuery的命名空间。

object1: Object 一个对象,它包含额外的属性合并到第一个参数

objectN: Object 包含额外的属性合并到第一个参数

Copy after login

1

$.extend({}, object1, object2);

Copy after login

1

2

3

4

5

6

jQuery.extend( [deep ], target, object1 [, objectN ] )

 

deep: Boolean 如果是true,合并成为递归(又叫做深拷贝)。

target: Object 对象扩展。这将接收新的属性。

object1: Object 一个对象,它包含额外的属性合并到第一个参数.

objectN: Object 包含额外的属性合并到第一个参数

Copy after login

1

$.extend(true, object1, object2);

Copy after login

【data()】

Store arbitrary data to the specified element and/or returns the set value

1

jQuery.data( element )

Copy after login

1

2

3

element:Element 要关联数据的DOM对象

key: String 存储的数据名

value:Object 新数据值

Copy after login

1

2

3

$.data(document.body, 'foo', 52);

$.data(document.body, 'bar''test');

console.log($.data( document.body, 'foo' ));//52console.log($.data( document.body ));//{foo: 52, bar: "test"}

Copy after login

【removeData()】

Delete A previously stored data fragment

1

jQuery.removeData( element [, name ] )

Copy after login

1

2

3

4

5

var div = $("div");

$.data(div, "test1""VALUE-1");

$.data(div, "test2""VALUE-2");

console.log($.data(div));//{test1: "VALUE-1", test2: "VALUE-2"}$.removeData(div, "test1");

console.log($.data(div));//{test2: "VALUE-2"}

Copy after login

Type detection

[type()]

The type() method is used to detect the type of javascript object

If the object is undefined or null, return the corresponding "undefined" or "null"

1

jQuery.type( undefined ) === "undefined"jQuery.type() === "undefined"jQuery.type( window.notDefined ) === "undefined"jQuery.type( null ) === "null"

Copy after login

If The object has an internal [[Class]] that is the same as the [[Class]] of a browser's built-in object, and the corresponding [[Class]] name is returned

1

jQuery.type( true ) === "boolean"jQuery.type( 3 ) === "number"jQuery.type( "test" ) === "string"jQuery.type( function(){} ) === "function"jQuery.type( [] ) === "array"jQuery.type( new Date() ) === "date"jQuery.type( new Error() ) === "error" jQuery.type( /test/ ) === "regexp"

Copy after login

So this method Similar to the encapsulated Object.prototype.toString() method in native javascript

1

2

function type(obj){return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();

}

Copy after login

[isArray()]

In native javascript, array detection is a classic Problem, when a web page contains multiple frames, array detection is no longer easy

jQuery provides the isArray() method to detect arrays

1

console.log($.isArray([]));//true

Copy after login

【isFunction()】

The isFunction() method is used to detect whether the incoming parameter is a function

1

console.log($.isFunction(function(){}));//true

Copy after login

If you use native javascript, you can use typeof to achieve it

1

console.log(typeof function(){});//"function"

Copy after login

【isNumeric()】

The isNumeric() method is used to detect whether the incoming parameter is a number

[Note] The parameter is a pure number or Numeric strings can be used

1

$.isNumeric("-10");  // true$.isNumeric(-10);  // true

Copy after login

If you use native javascript, you can use typeof, but the results are slightly different

1

console.log(typeof 10);//"number"console.log(typeof '10');//"string"

Copy after login

[isEmptyObject( )】

The isEmptyObject() method is used to detect whether an object is an empty object

1

jQuery.isEmptyObject({}) // truejQuery.isEmptyObject({ foo: "bar" }) // false

Copy after login

【isPlainObject()】

The isPlainObject() method is used To detect whether an object is a native object, that is, an object created through "{}" or "new Object"

1

console.log($.isPlainObject({}));//trueconsole.log($.isPlainObject(document.documentElement));//falseconsole.log($.isPlainObject(new Boolean(true)));//falseconsole.log($.isPlainObject(true));//false

Copy after login

【inArray()】

The inArray(value, array [, fromIndex]) method is similar to the indexOf() method of native JavaScript. It returns -1 when no matching element is found. If the first element of the array matches the parameter, then $.inArray() returns 0

The parameter fromIndex is the array index value, indicating where to start searching. The default value is 0

1

2

3

var arr = [1,2,3,'1','2','3'];

console.log(arr.indexOf('2'));//4console.log(arr.indexOf(3));//2console.log(arr.indexOf(0));//-1var arr = [1,2,3,'1','2','3'];

console.log($.inArray('2',arr));//4console.log($.inArray(3,arr));//2console.log($.inArray(0,arr));//-1

Copy after login

【makeArray()】

The makeArray() method is used to convert an array-like object into a real javascript array

1

console.log($.isArray({ 0: 'a', 1: 'b', length: 2 }));//falseconsole.log($.isArray($.makeArray({ 0: 'a', 1: 'b', length: 2 })));//true

Copy after login

If you use native javascript, you can use the slice() method to turn the array-like object into a real array

1

2

3

4

var arr = Array.prototype.slice.call(arrayLike);

 

Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })// ['a', 'b']Array.prototype.slice.call(document.querySelectorAll("div"));

Array.prototype.slice.call(arguments);

Copy after login

【unique()】

  unique()方法用于数组去重

1

2

3

var $arr = [document.body,document.body];

console.log($.unique($arr));//[body]var $arr = [1,2,1];

console.log($.unique($arr));//[2,1]

Copy after login

  使用原生javascript实现如下

1

2

3

4

5

Array.prototype.norepeat = function(){var result = [];for(var i = 0; i < this.length; i++){if(result.indexOf(this[i]) == -1){

            result.push(this[i]);

        }

    }return result;

}

Copy after login

1

2

3

var arr = [1,2,1];

console.log(arr.norepeat());//[1,2]var arr = [document.body,document.body];

console.log(arr.norepeat());//[body]

Copy after login

【grep()】

  查找满足过滤函数的数组元素。原始数组不受影响

1

2

3

jQuery.grep( array, function(elementOfArray, indexInArray) [, invert ] )

array: Array 用于查询元素的数组。function: Function() 该函数来处理每项元素的比对。第一个参数是正在被检查的数组的元素,第二个参数是该元素的索引值。该函数应返回一个布尔值。this将是全局的window对象。

invert: Boolean 如果“invert”为false,或没有提供,函数返回一个“callback”中返回true的所有元素组成的数组,。如果“invert”为true,函数返回一个“callback”中返回false的所有元素组成的数组。

Copy after login

  $.grep()方法会删除数组必要的元素,以使所有剩余元素通过过滤函数的检查。该测试是一个函数传递一个数组元素和该数组内这个的索引值。只有当测试返回true,该数组元素将返回到结果数组中。

  该过滤器的函数将被传递两个参数:当前正在被检查的数组中的元素,及该元素的索引值。该过滤器函数必须返回'true'以包含在结果数组项

1

2

3

var result = $.grep( [0,1,2], function(n,i){   return n > 0;

 });

console.log(result);//[1, 2]

Copy after login

1

2

3

var result = $.grep( [0,1,2], function(n,i){   return n > 0;

 },true);

console.log(result);//[0]

Copy after login

【merge()】

  合并两个数组内容到第一个数组

1

jQuery.merge( first, second )

Copy after login

1

console.log($.merge( [0,1,2], [2,3,4] ));//[0, 1, 2, 2, 3, 4]

Copy after login

 

其他

【proxy()】

  proxy()方法接受一个函数,然后返回一个新函数,并且这个新函数使用指定的this

  proxy()方法类似于bind(),但并不相同。区别在于,bind()方法是改变原函数的this指向,而proxy()方法是新建一个函数,并使用参数中的this指向,原函数的this指向并无变化

1

2

3

4

5

var a = 0;function foo(){

    console.log(this.a);

}var obj = {

    a:2};

foo();//0$.proxy(foo,obj)();//2foo();//0

Copy after login

  proxy()方法支持多种参数传递方式

1

2

3

4

5

function foo(a,b){

    console.log(a+b);   

}

 

$.proxy(foo,document)(1,2);//3$.proxy(foo,document,1,2)();//3$.proxy(foo,document,1)(2);//3

Copy after login

  在绑定事件时一定要合理使用proxy()方法的参数传递方式,否则事件还没有发生,可能函数已经被调用了

1

$(document).click($.proxy(foo,window,1,2))

Copy after login

【trim()】

  jQuery.trim()函数用于去除字符串两端的空白字符

  这个函数很简单,没有多余的参数用法

1

console.log($.trim("    hello, how are you?    "));//'hello, how are you?'

Copy after login

 【noop()】

  一个空函数

1

jQuery.noop() 此方法不接受任何参数

Copy after login

  当你仅仅想要传递一个空函数的时候,就用他吧

  这对一些插件作者很有用,当插件提供了一个可选的回调函数接口,那么如果调用的时候没有传递这个回调函数,就用jQuery.noop来代替执行

【now()】

  返回一个数字,表示当前时间

1

jQuery.now() 这个方法不接受任何参数

Copy after login

  $.now()方法是表达式(new Date).getTime()返回数值的一个简写

【parseHTML()】

  将字符串解析到一个DOM节点的数组中

1

2

3

4

jQuery.parseHTML( data [, context ] [, keepScripts ] )

data : String 用来解析的HTML字符串

context (默认: document): Element DOM元素的上下文,在这个上下文中将创建的HTML片段。

keepScripts (默认: false): Boolean 一个布尔值,表明是否在传递的HTML字符串中包含脚本。

Copy after login

  jQuery.parseHTML 使用原生的DOM元素的创建函数将字符串转换为一组DOM元素,然后,可以插入到文档中。

  默认情况下,如果没有指定或给定null or undefinedcontext是当前的document。如果HTML被用在另一个document中,比如一个iframe,该frame的文件可以使用

1

2

var result = $.parseHTML( "hello, my name is jQuery");

$('div').append(result);

Copy after login

【parseJSON()】

  接受一个标准格式的 JSON 字符串,并返回解析后的 JavaScript 对象

1

jQuery.parseJSON( json )

Copy after login

1

2

var obj = jQuery.parseJSON('{"name":"John"}');

console.log(obj.name === "John");//true

Copy after login

 

The above is the detailed content of jQuery common tool methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete WeChat friends? How to delete WeChat friends How to delete WeChat friends? How to delete WeChat friends Mar 04, 2024 am 11:10 AM

WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

See all articles