JQuery practical function usage summary, jquery function usage

Source: Internet
Author: User

JQuery practical function usage summary, jquery function usage

This article summarizes the common practical functions of jQuery in the form of examples. 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.

<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 repeated Elements

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

<Div> There are 6 divs in this document. </div> <div class = "dup"> </div> <div class = "dup"> </div> <div class =" dup "> </div> // you can specify all div, the get method is converted to a javascript array, with a total of six divvar divs =$ ("div "). get (); // merge the three div classes named dup into the first six divdivs = divs. concat ($ (". dup "). get (); alert (divs. length); // 9 div // filter out duplicate divs = jQuery. unqiue (divs); alert (divs. length); // 6 div

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(){  $("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, 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 div of a div =$ ("div") [0]; // store the key value on the div jQuery. data (div, "test", {first: 16, last: 'pizza'}) // read the value jQuery based on the key. data (div, "test "). firstjQuey. data (div, "test "). last

13. Remove the value stored on an element

<Div> value1 before creation: <span> </div> <div> value1 after creation: <span> </div> <div> value1 after removal: <span> </div> <div> value2 after removal: <span> </div> var div = $ ("div") [0]; // stores the value of jQuery. data (div, "test1", "VALUE-1"); // remove the VALUE jQuery. removeData (div, "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 + "<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. 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", 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.


Usage of the bind function in jQuery

Question 1:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "www.w3.org/..al.dtd">
<Html xmlns = "www.w3.org/5o/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Simple JQuery </title>
<Script type = "text/javascript" src = "js/jquery. js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ('# Mybtn'). bind ('click', {a: 'hello', B: 'World'}, myFun );
});

Function myFun (e ){
Alert (e. data. );
Alert (e. data. B)
}
</Script>
</Head>
<Body>
<Input type = "button" id = "mybtn" value = "Click me."/>
</Body>
</Html>
As in the preceding example, multiple parameters can be passed.

-------------------------------------------------------

Question 2:
$ ('<P> Test </p>'). appendTo ('. inner ');
$ ('. Inner'). append ('<p> Test </p> ');
The above is the difference between append () and appendTo (). Should it be clear at a glance?
AppendChild () is not a jquery method, but a javascript native method.

The relationship between append and appendChild is:
In fact, almost the same, append is implemented by calling appendChild, but a simple judgment is made before append. The following is the source code of jquery:

Append: function (... the remaining full text>

How to use functions in jquery

I use jquery-1.6.min.js, IE9, no error.

// Method 1
<Script type = "text/javascript">
<! --
$ (Document). ready (function (){
Var test = function (){
Alert ("test ");
};
Test ();
});
// -->
</Script>

// Method 2
<Script type = "text/javascript">
<! --
$ (Document). ready (function (){
Alert ("test ");
});
// -->
</Script>

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.