jQuery is a collection object. After finding the specified collection of elements through the $() method, a series of operations can be performed. For example, we operate $("li").css('') Set style values for all li. Because jQuery is a collection object, the css method must encapsulate a traversal method inside, which is called an implicit iteration process. To set the color for each li in the collection one by one, the method here is each
.each() method is a for loop iterator, which will iterate each DOM element in the jQuery object collection. Each time the callback function is executed, the current number of loops will be passed as a parameter (counting from 0)
So generally understand the 3 key points:
each is a wrapper iterator for a for loop
each is processed through callbacks, and will have two fixed actual parameters, index and element
this in each callback method points to the dom element of the current iteration
Look at a simple case
<ul>
<li>php.cn</li>
<li>Aaron</li>
</ul>
Start iterating li, loop 2 times
$("li").each(function(index, element) {
index index 0,1
element is the corresponding li node li ,li
this points to li
})
This way you can do some logical operations in the loop body. If you need to exit early, you can return false in the callback function. Abort the loop
Let’s write a piece of code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> .left { width: auto; height: 150px; } .left div { width: 150px; height: 120px; padding: 5px; margin: 5px; float: left; background: #bbffaa; border: 1px solid #ccc; } </style> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <h2>each方法</h2> <div class="left first-div"> <div class="div"> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> </div> <div class="div"> <ul> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </div> <br/> <button>点击:each方法遍历元素</button> <button>点击:each方法回调判断</button> <script type="text/javascript"> $("button:first").click(function() { //遍历所有的li //修改每个li内的字体颜色 $("li").each(function(index, element) { $(this).css('color','red') }) }) </script> <script type="text/javascript"> $("button:last").click(function() { //遍历所有的li //修改偶数li内的字体颜色 $("li").each(function(index, element) { if (index % 2) { $(this).css('color','blue') } }) }) </script> </body> </html>