JQuery practical function usage summary_jquery

Source: Internet
Author: User
This article mainly introduces the usage of jQuery practical functions and summarizes common functions and related skills of jQuery. For more information, see the following example. Share it with you for your reference. Example:

1. trim the string

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

2. traverse the set

It may be written as follows:

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

It is also possible to write as follows:

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 Arrays

Use the $. grep () method to filter arrays. Let's first look at the definition of the 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 preceding example:
① The second parameter of the grep method is the callback function, which receives two parameters, one being an array element and the other being an array index.
② Inv, the third parameter 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); // The result is: 4 5 6

If you set the third parameter of grep to true explicitly, what is the result?

Var arr = [1, 2, 3, 4, 5, 6]; arr = $. grep (arr, function (val, index) {return val> 3 ;}, true) console. log (arr); // The result is: 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

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 the 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 to an integer number array to 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) ? 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 input value, that is, the index.

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

6. convert an object to an array

$. MakeArray (object) converts an object similar to an array into a Javascript array.

First

Second

Third

Fourth

《script》 var elems = document.getElementsByTagName("p"); var arr = jQuery.makeArray(elems); arr.reverse(); $(arr).appendTo(document.body);《script》

7. Get an array without repeated Elements

Use $. unique (array) to return an array composed of Non-repeated elements in the original array.

There are 6 ps in this document.

// Convert all p and get methods to javascript arrays. A total of 6 pvar ps =$ ("p "). get (); // merge the three classes named dup into the first six pps = ps. concat ($ (". dup "). get (); alert (ps. length); // 9 p // filter out duplicate ps = jQuery. unqiue (ps); alert (ps. length); // 6 p

8. 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]

9. serialize the object into a query string

$. Param (params) converts the passed 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(){  $("p").text($.param(personObj)); });});

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

10. Some judgment Functions

$. IsArray (o) If o is a javascript array, true is returned. If it is a jquery object array similar to an array, false is returned.
$. IsEmptyObject (o) If o is a javascript Object that does not contain attributes, true is returned.
$. IsFunction (o) returns true if o is a javascript function.
$. IsPlainObject (o) If o is an Object created through {} or new Object (), true is returned.
$. IsXMLDoc (node) If node is a node in an XML document or an XML document, true is returned.

11. determine whether an element is included in another element.

$. Contains (container, containee) The second parameter is included

$.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 is a javascript object, and the second and third are key values.

// Obtain the javascript Object var p = $ ("p") [0] of p; // store the key value to jQuery on p. data (p, "test", {first: 16, last: 'pizza'}) // read the value jQuery based on the key. data (p, "test "). firstjQuey. data (p, "test "). last

13. Remove the value stored on an element

Value1 before creation:

Value1 after creation:

Value1 after removal:

Value2 after removal:

Var p = $ ("p") [0]; // The stored value jQuery. data (p, "test1", "VALUE-1"); // remove the VALUE jQuery. removeData (p, "test1 ");

14. Bind The context of the Function

JQuery. proxy (function, context) returns a new function. The context is context.

 $(document).ready(function(){ var objPerson = {  name: "John Doe",  age: 32,  test: function(){   $("p").after("Name: " + this.name + "
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. parse JSON

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

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

16. Expression evaluate

Sometimes, you can use jQuery. globalEval (code) to execute a piece of code in a global context ). The code type is a string.

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

17. dynamically load scripts

$ (Selector ). getScript (url, success (response, status) is used to dynamically load js files. The first parameter is the js file path, and the second parameter is optional, indicating that callback is successful for obtaining js files.

$.getScript( "ajax/test.js?6.1.3", 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 this article provides some reference value for jQuery program design.

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.