search
HomeWeb Front-endJS TutorialjQuery common tool methods

jQuery common tool methods

Jun 26, 2017 pm 02:32 PM
jqueryCommon toolmethod

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

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

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

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

【contains()】

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

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

【extend()】

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

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

target: Object 一个对象,如果附加的对象被传递给这个方法将那么它将接收新的属性,如果它是唯一的参数将扩展jQuery的命名空间。
object1: Object 一个对象,它包含额外的属性合并到第一个参数
objectN: Object 包含额外的属性合并到第一个参数
$.extend({}, object1, object2);
jQuery.extend( [deep ], target, object1 [, objectN ] )

deep: Boolean 如果是true,合并成为递归(又叫做深拷贝)。
target: Object 对象扩展。这将接收新的属性。
object1: Object 一个对象,它包含额外的属性合并到第一个参数.
objectN: Object 包含额外的属性合并到第一个参数
$.extend(true, object1, object2);

【data()】

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

jQuery.data( element )
element:Element 要关联数据的DOM对象
key: String 存储的数据名
value:Object 新数据值
$.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"}

【removeData()】

Delete A previously stored data fragment

jQuery.removeData( element [, name ] )
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"}

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"

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

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

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"

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

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

[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

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

【isFunction()】

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

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

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

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

【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

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

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

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

[isEmptyObject( )】

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

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

【isPlainObject()】

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

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

【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

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

【makeArray()】

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

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

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

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);

【unique()】

  unique()方法用于数组去重

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

  使用原生javascript实现如下

Array.prototype.norepeat = function(){var result = [];for(var i = 0; i 
var arr = [1,2,1];
console.log(arr.norepeat());//[1,2]var arr = [document.body,document.body];
console.log(arr.norepeat());//[body]

【grep()】

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

jQuery.grep( array, function(elementOfArray, indexInArray) [, invert ] )
array: Array 用于查询元素的数组。function: Function() 该函数来处理每项元素的比对。第一个参数是正在被检查的数组的元素,第二个参数是该元素的索引值。该函数应返回一个布尔值。this将是全局的window对象。
invert: Boolean 如果“invert”为false,或没有提供,函数返回一个“callback”中返回true的所有元素组成的数组,。如果“invert”为true,函数返回一个“callback”中返回false的所有元素组成的数组。

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

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

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

【merge()】

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

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

 

其他

【proxy()】

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

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

var a = 0;function foo(){
    console.log(this.a);
}var obj = {
    a:2};
foo();//0$.proxy(foo,obj)();//2foo();//0

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

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

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

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

【trim()】

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

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

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

 【noop()】

  一个空函数

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

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

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

【now()】

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

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

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

【parseHTML()】

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

jQuery.parseHTML( data [, context ] [, keepScripts ] )
data : String 用来解析的HTML字符串
context (默认: document): Element DOM元素的上下文,在这个上下文中将创建的HTML片段。
keepScripts (默认: false): Boolean 一个布尔值,表明是否在传递的HTML字符串中包含脚本。

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

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

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

【parseJSON()】

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

jQuery.parseJSON( json )
var obj = jQuery.parseJSON('{"name":"John"}');
console.log(obj.name === "John");//true

 

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
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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.