Home  >  Article  >  Web Front-end  >  Summary of jQuery practical function usage_jquery

Summary of jQuery practical function usage_jquery

WBOY
WBOYOriginal
2016-05-16 16:38:381503browse

This article summarizes jQuery’s common practical functions in the form of examples. Share it with everyone for your reference. Specific examples are as follows:

1. Trim string

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

2. Traverse the collection

might be written like this:

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

It is also possible to write:

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

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

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

3. Filter array

Use the $.grep() method to filter the array. 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. The callback function receives two parameters, one is the element of the array, and the other is the index of the array.
② The third parameter inv of the grep method is undefined by default, so !!inv is false, that is, the default value of inv is false

Example 1: int type array

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

What will be the result 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);//结果是: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 meet the callback function will be filtered out.

Example 2: object type array

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 array

Use $.map(arr, callback) to call the callback function for each element of the array and return a new array

Add 1 to each element of the array:

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

Convert the string array into an integer array and determine whether the array element is a number:

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

Merge the converted array into the original array:

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

5. Return the index of the array element

Use $.inArray(value, array) to return the subscript of the first occurrence of the passed in value, that is, the index.

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

6. Convert the object into an array

$.makeArray(object) converts the passed array-like object into 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 consisting of unique elements in 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>
//把到所有div,get方法转换成javascript数组,总共6个div
var divs = $("div").get();
//再把3个class名为dup的div合并到前面的6个div
divs = divs.concat($(".dup").get());
alert(divs.length); //9个div
//过滤去掉重复
divs = jQuery.unqiue(divs);
alert(divs.length);//6个div

8. Merge 2 arrays

$.merge(array1, array2) merges the second array 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]

9. Serialize the object into a query string

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

$(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));
 });
});

Result: firstname=John&lastname=Doe&age=50&eyecolor=blue

10. Some judgment functions

$.isArray(o) If o is a javascript array, it returns true. If it is an array-like jquery object array, it returns false
$.isEmptyObject(o) Returns true if o is a javascript object that does not contain attributes
$.isFunction(o) returns true if o is a javascript function
$.isPlainObject(o) Returns true if o is an object created through {} or new Object()
$.isXMLDoc(node) If node is an XML document or a node in an XML document, it returns true

11. Determine whether an element is contained in another element

The second parameter of $.contains(container, containee) is contained

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

12. Store the value on an element

$.data(element, key, value) The first one is the javascript object, and the second and third ones are the key value.

//得到一个div的javascript对象
var div = $("div")[0];
//把键值存储到div上
jQuery.data(div, "test",{
  first: 16,
  last: 'pizza'
})
//根据键读出值
jQuery.data(div, "test").first
jQuey.data(div, "test").last

13. Remove the 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 ];
//存储值
jQuery.data( div, "test1", "VALUE-1" );
//移除值
jQuery.removeData( div, "test1" );

14. Context of bound function

jQuery.proxy(function, context) returns a new function function, the context is 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, when you click the button, the test method is executed, but the context of the test method is set.

15. Parse JSON

jQuery.parseJSON(json) The type of the first parameter json is a string.

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

16. Expression evaluation

Sometimes, if you want a piece of code to be executed in the global context, you can use jQuery.globalEval(code). The type of code is string.

function test() {
 jQuery.globalEval( "var newVar = true;" )
}
test();

17. Dynamic loading script

$(selector).getScript(url,success(response,status)) is used to dynamically load js files. The first parameter is the file path of js. The second parameter is optional and represents the callback for successfully obtaining 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 what is described in this article has certain reference value for everyone’s jQuery programming.

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