Summary of common methods of jQuery


$.grep( array, function(elementOfArray, indexInArray) [, invert ] )

Function: find the array elements that meet the filter function:

<script src="js/jquery1.42.min.js"></script>    <script type="text/javascript">        $(function () {            var arr = [23,45,5,1,4,67,8,100,-2];            var arrGrep = $.grep(arr, function (element,index) {                return (index<5)&&(element != 4);//An array}) alert (arrgrep) is returned as a whole// 23,45,5,1        })</script>


$.map( array, callback(elementOfArray, indexInArray) )

Function: convert all elements in one array to another array. ​​​​​​​

 <script src="js/jquery1.42.min.js"></script>    <script type="text/javascript">        $(function () {            var arr = [5,1,4,67,8,100,-2];            var arrMap = $.map(arr, function (element,index) {                //  return (index<3)&&(element != 4); Here, if (index < 3 & & element < 4) {return element;}}) is returned by Boolean value; alert(arrMap);// 1        })</script>


mouseover/mouseout events are triggered when the mouse enters / leaves an element or its descendants.
The mouseover event is used most of the time with the mouseout event.

mouseover/mouserout events due to the bubbling mechanism, Front end training It is often triggered accidentally when it is not needed, resulting in some script problems. ​​​​​​​


mouseenter/mouseleave is triggered when and only when the mouse enters the selected element, and will not be triggered when the mouse passes through any child element. It doesn't care if the target element has child elements.

focusin() and focusout()

. focusin(): this event is triggered when an element or its child elements get focus
. focusout(): this event is triggered when an element or its child elements lose focus

Unlike the focus() method, the focusin() method is also triggered when any child element obtains focus. ​​​​​​​

<body>    <p><input type="text"> <span>focusin fire</span></p>    <p><input type="password"> <span>focusin fire</span></p>    <script>    $( "p" ).focusin(function() {    $( this ).find( "span" ).css( "display", "inline" ).fadeOut( 1000 );    });</script></body>

eq() and get()

. get(): get a corresponding DOM element through jQuery object.
. eq(): construct a new jQuery object from an element of the collection

eq returns a jQuery object, and get returns a DOM object. For example:

$( "li" ).get( 0 ).css("color", "red"); //Error $("Li") eq( 0 ). css("color", "red"); // correct

So what are DOM objects and jQuery objects?

DOM object is the object obtained with js, while juqery object is the object obtained with the selector of jQuery class library.

For example: VAR $obj = $("div")// JQuery object

The get method essentially converts jQuery objects into DOM objects, but css belongs to the jQuery constructor. This method does not exist in DOM. If we need to use jQuery methods, we must write as follows:

var li = $("li").get(0);$(li).css("color","black");//Package with $


filter()method:Filters out the collection of elements that match the specified expression.

This method is used to narrow the scope of matching. Separate multiple expressions with commas.

filter(expression): (string | function) if the parameter is a string, formulate a jQuery selector to delete all elements that do not match the selector from the wrapper set, and finally leave the elements that match the selector; If the parameter is a function, it is used to determine the filter criteria. Call this function once for each element in the wrapper set, and any element whose return value is false will be deleted from the wrapper set.

The following code means: keep the first element and the element with the select class

HTML code:

 <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>

jQuery Code:

 $("p").filter(".selected, :first")


 <p>Hello</p>, <p class="selected">And Again</p> 

Let's take another example of function. A function is used as a collection of test elements. It accepts a parameter index, which is the index of the element in the jQuery collection. In the function, this refers to the current DOM element.

HTML code:

 <p><ol><li>Hello</li></ol></p><p>How are you?</p>

jQuery Code:

$("p").filter(function(index) {  return $("ol", this).length == 0;});


<p>How are you?</p>  

.bind(),. live() and delegate() method

. bind(): the most basic way to bind event handlers is to use Bind() method. Like the live() method, it accepts two parameters:

.bind(event type, event handler)

There are two methods to bind event handler functions:

$(document).ready(function(){    $('.mydiv').bind('click',test);        function test(){        alert("Hello World!");    }});

Anonymous functions can also be used for event handling functions, as shown below:

$(document).ready(function(){        $("#mydiv").bind("click",function(){            alert("Hello World!");        })    });

. live(): the only difference between the live method and the bind method is Live () works not only on elements that currently exist in the DOM, but also on elements that may exist (dynamically generated) in the future

$(document).ready(function(){        $('.box').live('click',function(){            $(this).clone().appendTo('.container');        });    });        <div class="container">        <div class="box"></div>    </div>

The disadvantage of using live method to bind events is that it cannot use chain call. Is there a method that can bind events like live method and support chain call? The answer is the following delegate method.

delegate() method: add one or more event handlers for the specified element (the child element of the selected element),

And specify the function to run when these events occur. from jQuery 1.7 Start,`.delegate()`Has been`.on()`Method substitution.


 $(selector).delegate(childSelector,event type,function)

Parameter Description:

childSelector is required. Specifies one or more child elements of the event handler to attach.

Event is required. One or more specified events. Multiple event values are separated by spaces. Must be a valid event.

Function is required. Specifies the function to run when an event occurs. ​​​​​​​

$(document).ready(function(){        $('.container').delegate('.box','click',function(){            $(this).clone().appendTo('.container');        });    });

delegate() is used in the following two cases:

1. If you have a parent element and need to add an event to its child element, you can use delegate(). The code is as follows:

$("ul").delegate("li", "click", function(){

2. When an element is not available in the current page, you can use delegate()

end() method

 end()Method: in jquery Called within the command chain to return to the previous wrapper set.

Each filter method is pushed into the stack. When we need to return to the previous state, we can use end() to exit the stack to return to the previous state in the stack.

The end() method ends the recent filtering operation in the current chain and restores the matching element set to its previous state. ​​​​​​​

<head>    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />    <title></title>    <script src=""></script></head><body>    <ul class="one">    <li class="two">item 1</li>    <li>item 2</li>    <li class="three">item 3</li></ul>
<script type="text/javascript">    $('').find(".two").css("color","red").find('.three').css("background","blue");</script>

In the above code example, we can only see that the font color of item 1 has changed, while the background color has not changed. that is because
The previous status of the second find() method returns the object with the class value of two in red font. Therefore, the second find() will only find the object in < UL class = "one" > Two, use the end() method to modify the code of the chain operation as follows:

<script type="text/javascript">    $('').find(".two").css("color","red").end().find('.three').css("background","blue");</script>

The end() method returns the status before calling find(), that is, $(' ')


 `toggleClass()method:`If the specified class name does not exist in the element, add the specified class name; If the element already has the specified class name, the specified class name is deleted from the element.
 css(name,value)Method: set the specified value to the specified value of each matched element css Style properties

wrap() and wrapInner()

 `wrap()and wrapInner(): `The former wraps all matched elements with structured tags of other elements; The latter will be the child content of each matching element(Include text nodes)Use one HTML Wrap the structure.

Take the following example of wrap():
Use the content of the original div as the class of the new div, and wrap each element

HTML code:

<div class="container">  <div class="inner">Hello</div>  <div class="inner">Goodbye</div></div>

jQuery Code:

$('.inner').wrap(function() {  return '<div class="' + $(this).text() + '" />';});


<div class="container">  <div class="Hello">    <div class="inner">Hello</div>  </div>  <div class="Goodbye">    <div class="inner">Goodbye</div>  </div></div>

Next, take a look at the following example of wrapInner():

Use the content of the original div as the class of the new div, and wrap each element

HTML code:

<div class="container">  <div class="inner">Hello</div>  <div class="inner">Goodbye</div></div>

jQuery Code:

$('.inner').wrapInner(function() {  return '<div class="' + $(this).text() + '" />';});


<div class="container">  <div class="inner">    <div class="Hello">Hello</div>  </div>  <div class="inner">    <div class="Goodbye">Goodbye</div>  </div></div>

detach, empty, and remove methods

. detach ([selector]): remove all matching elements from the dom. When you need to remove an element and insert it into the DOM soon, you need to use the detach method.

. empty(): this method removes not only child elements (and other descendant elements), but also the text in the element. Because, according to the description, any text string in the element is regarded as the child node of the element.

. remove ([selector]): remove the element from the DOM, and remove the event and jQuery {data on the element at the same time

Example of empty():

 <ul class="one">    <li class="two">item 1</li>    <li>item 2</li>    <li class="three">item 3</li></ul>
<script type="text/javascript">    $(".two").empty();//The item 1 text node is removed and the dot of li is still there, which proves that li has not been removed < / script >

Take the following example of remove():

Description: deletes all paragraphs from the DOM

HTML code:

<p>Hello</p> how are <p>you?</p>

jQuery Code:



how are

val() method

val(): Gets the current value of the matching element.

Description: gets the value in the text box

jQuery Code:


jQuery Code:

$("input").val("hello world!");

each() and map()

each()and map()method: each The original array is returned, and a new array will not be created. and map Method returns a new array. If used unnecessarily map,It may cause a waste of memory.

each method:

Define an empty array and add ID value to the array through each method; Finally, after the array is converted into a string, alert the value; ​​​​​​​

$(function(){    var arr = [];    $(":checkbox").each(function(index){        arr.push(;    });    var str = arr.join(",");    alert(str);})

map method:

Execute return this for each: checkbox id; And automatically save these return values as jQuery objects, then use the get method to convert them into native Javascript arrays, then use the join method to convert them into strings, and finally alert this value; ​​​​​​​

$(function(){    var str = $(":checkbox").map(function() {        return;    }).get().join();    alert(str);})

When you need the value of an array, it is convenient to use the map method.

For a more detailed discussion, please click my other article: explain the use of jQuery built-in functions map() and each()


$(selector) of jQuery each() function can traverse the child elements selected in the loop, while jQuery's $ each() function can traverse any collection, including objects and arrays. It receives the collection to be traversed and a callback function. The callback function passes the subscript of an array and the value of the array corresponding to this subscript each time. ​​​​​​​


Array instance

$.each( [ "one", "two", "three" ], function( i, l ){    alert( "index #"+ I +": "+ L);}); callback (index, index value)

DEMO: ​​​​​​​

index 0: oneindex 1: two;index 2: three

Object instance

$.each({ name: "trigkit4", lang: "JS" }, function( k, v ) {    alert( "Key: " + k + ", Value: " + v );});callback(key,value)


 Key: name, Value: trigkit4 Key: lang, Value: JS


Description: executes all handlers and actions according to the given event type bound to the matching element.

When the corresponding event occurs, any pass on(),. The event handler bound by bind() or a shortcut method will be triggered. However, they can be used trigger() method is triggered manually. ​​​​​​​

<script type="text/javascript">    $(document).bind('abc',function(){            console.log('hello');});    $(document).trigger('abc');    //Output  'hello';</script>

. attr() and prop()

. attr(): get the value of the attribute of the first element in the matched element set or set one or more attributes of each matched element.

. prop(): ditto
Before jQuery 1.6 When the attr() method takes the value of some , attribute , it will return the value of , property , which leads to inconsistent results. Starting with jQuery 1.6 The prop() method returns the value of {property}, and The attr() method returns the value of # attributes #.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be used The prop() method takes value or assigns value.

They have no corresponding attributes, only properties.

. after() and insertAfter()


Insert a jQuery object (similar to an array of DOM elements) after all paragraphs.

HTML code:

<b>Hello</b><p>I would like to say: </p>

jQuery Code:

$("p").after( $("b") );


<p>I would like to say: </p><b>Hello</b>


Insert all paragraphs after an element. And $("#foo") Same as after ("P")

HTML code:

<p>I would like to say: </p><div id="foo">Hello</div>

jQuery Code:



<div id="foo">Hello</div><p>I would like to say: </p>

. before() and insertBefore()


Insert a jQuery object (similar to an array of DOM elements) before all paragraphs.

HTML code:

<p>I would like to say: </p><b>Hello</b>

jQuery Code:

$("p").before( $("b") );


<b>Hello</b><p>I would like to say: </p>

. append() and appendTo()


Description: append some HTML tags to all paragraphs.

HTML code:

<p>I would like to say: </p>

jQuery Code:



<p>I would like to say: <b>Hello</b></p>


Description: add a new paragraph to div and add a class

HTML code:


jQuery Code:

 $("<p/>")   .appendTo("div")   .addClass("test")   .end()   .addClass("test2");


<div><p class="test test2"></p></div><div><p class="test"></p></div>

. prepend() and prependTo()


Description: prefix all paragraphs with a jQuery object (similar to an array of DOM elements).

HTML code:

<p>I would like to say: </p><b>Hello</b>

jQuery Code:

$("p").prepend( $("b") );


<p><b>Hello</b>I would like to say: </p>


Description: append all paragraphs to the element with ID value foo.

HTML code:

<p>I would like to say: </p><div id="foo"></div>

jQuery Code:



<div id="foo"><p>I would like to say: </p></div>


1. .insertAfter()and.after(): Insert the element from behind outside the existing element 2. .insertBefore()and.before(): Insert the element from the front outside the existing element
3. .appendTo()and.append(): Inside an existing element, insert the element from behind
4. .prependTo()and.prepend()  : Inside an existing element, insert the element from the front

.data( key, value )

The. data() method allows us to bind arbitrary types of data on DOM elements,

$("div").data("test", { first: 16, last: "pizza!" });

.promise( [type ] [, target ] )

In Javascript, there is another asynchronous processing mode called "Promises", so the CommonJS Standard Committee issued a specification, which calls this "API" as "Promises".

The concept behind Promise # is very simple and has two parts:

Deferreds,Define unit of work, Promises,from Deferreds Data returned.

An important difference between Promise and callback is that you can append processing handles after the state of Promise changes to resolved. This allows you to transfer data regardless of whether it has been fetched by the application, then cache it, etc., so you can perform operations on the data regardless of whether it is already or will be available.

You can append multiple processes (then()) to a # promise #. The Promise API} is fun in that it allows Chaining:

<!-- lang: js -->promise  .then(doSomething)  .then(doSomethingElse)  .then(doSomethingMore)  .catch(logError);

Keywords: Javascript Front-end JQuery

Added by Cong on Mon, 14 Feb 2022 07:00:02 +0200