Understand $.each and $ (selector).

Source: Internet
Author: User

$.each: This method is used to traverse any collection, including arrays and objects

$ (selector). Each: This method is used to traverse the Jquery object

Syntax: $.each (Obj,callback,args)

① traversing an array

var arry = ["A", "B", "C", "D",...];

$.each (Arry,function (index,value) {...})

callback function: Index stands for an array of indexes , and valuerepresents the values in the array

② traversing Json objects

var json = {key1:value1, key2:value2, key3:value3}

$.each (JSON, function (Key,value) {...})

callback function:key represents the key in the JSON object, value represents the value in the JSON object

③ traversal of jquery objects

var doms = $ ("div"); The//jquery object itself is a collection that can be indexed to convert a jquery object to a DOM object

$.each (Doms, function (Index,value) {..})

callback function: Index stands for jquery Index in object, value stands for jquery object dom objects, also through this get the same dom object

Another way to ③ is $ ("div"). each (function (Index,value) {...})

For the $.each method, you can exit the loop by return false in the callback function if return True is equivalent to the continue in the For loop

question: why Span style= "FONT-FAMILY:CALIBRI;" lang= "en-us" >$ (). each callback function This No jquery Object But dom object

Because $ (). the essence of each method is implemented by calling $.each , by analyzing the $.each source, we can see callback.apply (Object[i++],args ) this piece of code

For$ (). eachPassed in.ObjectIsjquery objects, while object[i++] will jquerydomapply method hijack the properties of the object, then thisdom object

We often see this in the Jquery plugin, through the above analysis, I think I should understand

$.fn.test = function (option) {

Return This.each (function () {// this is a Jquery object

alert (this);// and This is a Dom object

})

}

Understand $.each and $ (selector).

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.