Home  >  Article  >  Web Front-end  >  jQuery common tool methods

jQuery common tool methods

巴扎黑
巴扎黑Original
2017-06-26 14:32:471037browse

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

Element related

【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 related

【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

Array related

【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 < this.length; i++){if(result.indexOf(this[i]) == -1){
            result.push(this[i]);
        }
    }return result;
}
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