Summary of usage of jQuery utility functions

  • 2020-03-30 03:48:51
  • OfStack

This article summarizes the common utility functions of jQuery in the form of examples. Share with you for your reference. Specific examples are as follows:

Trim the string


$('#id').val($.trim($('#someid').val()))
 

2. Traverse the collection

It might say:


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

Or you might write:


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

But with the $.each function, you can write:


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

Filter the array

Use the $.grep() method to filter arrays. Let's first look at the definition of grep method:


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 above example:
The second parameter of the grep method is the callback function, which receives two parameters, one is the element of the array, the other is the index of the array.
Grep method of the third parameter inv, the default is undefined, so!! Inv is false, that is, the default value of inv is false

Example 1: array of type int


var arr = [1, 2, 3, 4, 5, 6];
arr = $.grep(arr, function(val, index){
  return val > 3;
})
console.log(arr);//The result: 4, 5, 6

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


var arr = [1, 2, 3, 4, 5, 6];
arr = $.grep(arr, function(val, index){
  return val > 3;
}, true)
console.log(arr);//The result: 1, 2, 3

As you can see, 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: an array of type object


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. Convert arrays

The callback function is called for each element of the array using $.map(arr, callback) and returns a new array

Add 1 to each element of the array:


var oneBased = $.map([0, 1, 2, 3, 4], function(value){return value +1;})

Converts the string array to an integer array of Numbers to determine whether the array elements are Numbers:


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:


var chars = $.map(['this','that'], function(value){return value.split(' ')});

Returns the index of an array element

Use $.inarray (value, array) to return the index of the first occurrence of the incoming value.


var index = $.inArray(2, [1, 2, 3]);

6. Convert objects to arrays

$.makearray (object) converts an array-like object passed in to a Javascript array.


<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
  var elems = document.getElementsByTagName("div");
  var arr = jQuery.makeArray(elems);
  arr.reverse();
  $(arr).appendTo(document.body);
</script>

7. Get an array without duplicate elements

Use $.unique(array) to return an array of non-repeating elements from the original array.


<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>
//I'm going to convert all the divs, the get method, into a javascript array, six divs
var divs = $("div").get();
//Add the three divs with the class name dup to the previous six divs
divs = divs.concat($(".dup").get());
alert(divs.length); //Nine div
//Filter out duplicates
divs = jQuery.unqiue(divs);
alert(divs.length);//Six div

Merge two arrays

Merge (array1, array2) combines the second number into the first array and returns the first array.


var a1 = [1, 2];
var a2 = [2, 3];
$.merge(a1, a2);
console.log(a1);//[1, 2, 2, 3]

Serialize the object into a query string

$.param(params) converts the incoming jquery object or javascript object into a string.


$(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) returns true if o is a javascript array, or false if it is an array of jquery objects
$.isemptyobject (o) returns true if o is a javascript object with no attributes
$.isfunction (o) returns true if o is a javascript function
$.isplainobject (o) returns true if o is an Object created by {} or new Object()
$.isxmldoc (node) returns true if the node is an XML document or a node in an XML document

11. Determine whether an element is contained in another element

Contains (container, containee) the second parameter is contained


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

Store a value on an element

$.data(element, key, value) the first is a javascript object, the second and third are key values.


//You get a javascript object of div
var div = $("div")[0];
//Store the key value on div
jQuery.data(div, "test",{
  first: 16,
  last: 'pizza'
})
//Read the value by the key
jQuery.data(div, "test").first
jQuey.data(div, "test").last

Removes a value stored on an element


<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 ];
//Stored value
jQuery.data( div, "test1", "VALUE-1" );
//Remove the value
jQuery.removeData( div, "test1" );

The context of the bound function

JQuery. Proxy (function, context) returns a new function with context.


 $(document).ready(function(){
 var objPerson = {
  name: "John Doe",
  age: 32,
  test: function(){
   $("p").after("Name: " + this.name + "<br> Age: " + this.age);
  }
 };
 $("button").click($.proxy(objPerson,"test"));
});

Above, click the button to execute the test method, but the context of the test method is set.

15. Parsing JSON

The first parameter json is of type string.


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

16. Evaluate the expression

Dynamically load scripts

$(selector).getscript (url,success(response,status)) is used to dynamically load the js file. The first parameter is the js file path, and the second parameter is optional, indicating a successful callback to the js file.


$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
 console.log( data ); // Data returned
 console.log( textStatus ); // Success
 console.log( jqxhr.status ); // 200
 console.log( "Load was performed." );
});

I believe that this article has a certain reference value for your jQuery programming.


Related articles: