Summary of the usage of jquery utility functions

Source: Internet
Author: User

1. Trimming strings

?
1 $(‘#id‘).val($.trim($(‘#someid‘).val()))

2. Iterating through the collection

It may be written like this:

?
1234 varanArray = [‘one‘,‘two‘];for(var n = 0; n < anArray.length; n++){  }

It is also possible to write:

?
1234 varanObject = {one: 1, two: 2};for(var p in anObject){  }

But with the $.each function, it can be written like this:

?
12345678 varanArray = [‘one‘,‘two‘];$.each(anArray, funtion(n, value){   })var anObject = {one: 1, two: 2};$.each(anObjct, function(name,value){  })

3. Filtering arrays

Use the $.grep () method to filter the array. First look at the definition of the grep method:

?
1234567891011 grep: function(elems, callback, inv){  var ret = [], retVal;  inv = !!inv;  for(var i = 0; length = elems.length; i < length; i++){    retVal = !!callback(elems[i],i)    if(inv !== retVal){      ret.push(elems[i]);    }  }  return ret;}

In the example above:
The second parameter of the ①grep method is a callback function that receives 2 parameters, one that is an element of the array, and one that is the index of the array.
The third parameter of the ②grep method is inv, which by default is undefined, so!! Inv is false, that is, the default value for Inv is False

Example 1:int type array

?
12345 vararr = [1, 2, 3, 4, 5, 6];arr = $.grep(arr, function(val, index){  returnval > 3;})console.log(arr);//结果是:4 5 6

What happens if you explicitly set the third parameter of grep to true?

?
12345 vararr = [1, 2, 3, 4, 5, 6];arr = $.grep(arr, function(val, index){  returnval > 3;}, true)console.log(arr);//结果是:1 2 3

It can be seen that when the third parameter of the Grep method is set to True, the array elements that do not conform to the callback function are filtered out.

Example 2:object type array

?
12345678910111213141516171819 var arr = [  {    first: "Jeffrey",    last: ‘Way‘  },{    first: ‘Allison‘,    last: ‘Way‘  },{    first: ‘John‘,    last: ‘Doe‘  },{    first: ‘Thomas‘,    last: ‘Way‘  };  arr = $.grep(arr, function(obj, index){    return obj.last === ‘Way‘;  });  console.log(arr);];

4. Converting an array

Call the callback function for each element of the array using $.map (arr, callback) and return a new array

Add 1 to each element of the array:

?
1 varoneBased = $.map([0, 1, 2, 3, 4], function(value){returnvalue +1;})

Converts a string array into an integer array of numbers, judging whether the array element is a number:

?
12345 var strings = [‘1‘, ‘2‘, ‘3‘,‘4‘,‘S‘,‘6‘];var values = $.map(strings, function(value){  var result = new Number(value);  return isNaN(result) ? null : result;})

Merge the converted array into the original array:

?
1 varchars = $.map([‘this‘,‘that‘], function(value){returnvalue.split(‘ ‘)});

5. Returns the index of an array element

Returns the index of the first occurrence of the passed-in value using $.inarray (value, array).

?
1 varindex = $.inArray(2, [1, 2, 3]);

6. Convert an object to an array

$.makearray (object) Converts an object that is passed into a similar array into a JavaScript array.

?
12345678910 <div>first</div <DIV>SECOND</DIV> <div>third </div> <DIV>FOURTH</DIV> < Script> &NBSP;&NBSP; var elems = document.getElementsByTagName ( &NBSP;&NBSP; var arr = Jquery.makearray (elems); &NBSP;&NBSP; arr.reverse (); &NBSP;&NBSP; $ (arr). AppendTo (document.body); </SCRIPT>

7. Get an array with no duplicate elements

Uses $.unique (array) to return an array of elements that are not duplicates in the original array.

?
1234567891011121314 <div>There are 6 divs in this document.</div><div></div><div class="dup"></div><div class="dup"></div><div class="dup"></div><div></div>//把到所有div,get方法转换成javascript数组,总共6个divvar divs = $("div").get();//再把3个class名为dup的div合并到前面的6个divdivs = divs.concat($(".dup").get());alert(divs.length); //9个div//过滤去掉重复divs = jQuery.unqiue(divs);alert(divs.length);//6个div

8. Merging of 2 arrays

$.merge (Array1, Array2) merges the second array into the first array and returns the first array.

?
1234 vara1 = [1, 2];vara2 = [2, 3];$.merge(a1, a2);console.log(a1);//[1, 2, 2, 3]

9. Serializing objects into query strings

The $.param (params) converts an incoming jquery object or JavaScript object into a string form.

?
12345678910 $(document).ready(function(){ personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue";  $("button").click(function(){  $("div").text($.param(personObj)); });});

Results: Firstname=john&lastname=doe&age=50&eyecolor=blue

10. Some Judgment functions

$.isarray (o) If O is an array of JavaScript, returns True if it is an array of jquery objects similar to array, returns false
$.isemptyobject (o) returns True if O is a JavaScript object that does not contain a property
$.isfunction (o) If O is a JavaScript function returns true
$.isplainobject (o) returns True if O is an object created through {} or New object ()
$.isxmldoc (node) returns True if node is an XML document or an XML document.

11. Determine if an element is contained in another element

$.contains (container, Containee) The second parameter is the one that is included

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

12. Storing values on an element

$.data (element, key, value) The first is a JavaScript object, and the second and third is the key value.

?
12345678910 // Get a div for JavaScript object var div = $ ( " div " ) [0]; //store the key value on the DIV jquery.data (Div, "test" ,{ &NBSP;&NBSP; first:16, &NBSP;&NBSP; last: ' pizza ' }) //read-out value by key jquery.data ( Div, "test" ). First Jquey.data (Div,

13. Remove the value stored on an element

?
123456789 <div>value1 before creation: <span></span></div> <div>value1 after creation: <SPAN></SPAN></DIV> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div> var div = $ ( " div " ) [0]; //Store value jquery.data (Div, "test1" , "VALUE-1" //Remove value jquery.removedata (Div, "Test1"

JQuery Utility Function Usage Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.