jQuery: each() method
Định nghĩa và sử dụng
.each(): Thực hiện một hành động cho mỗi phần tử, mỗi lần thực hiện một phần tử, để làm được điều này ta cần sử dụng phương thức $(this).
Cú pháp
$('selecter').each(function(index){
//...
});
Ví dụ 1
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Each()</title> <script src="https://code.jquery.com/jquery-latest.js"></script> <style> li{font-size: 30px} .list0 { color: red; } .list1 { color: blue; } .list2 { color: yellow; } .list3 { color: green; } .list4 { color: gray; } .list5 { color: pink; } </style> <script> $(function(){ $('li').each(function(index){ $(this).click(function(){ $(this).addClass("list"+index); }); }); }); </script> </head> <body> <h2>Click vào từng mục => Đổi màu</h2> <ul> <li>list 01</li> <li>list 02</li> <li>list 03</li> <li>list 04</li> <li>list 05</li> <li>list 06</li> </ul> </body> </html>
Demo:
Khi sử dụng .each(), phương thức click() sẽ chỉ tác động lên từng phần tử riêng lẻ (click lên từng phần tử li để thấy kết quả).
Ví dụ 2
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Each2</title> <script src="https://code.jquery.com/jquery-latest.js"></script> <style> .over{ color: red; } </style> <script> $(function(){ $('li').each(function(){ $(this).hover(function(){ $(this).addClass("over"); },function(){ $(this).removeClass("over"); }); }); }); </script> </head> <body> <h3>Di chuyển chuột over từng mục => Đổi màu</h3> <ul> <li>list 01</li> <li>list 02</li> <li>list 03</li> <li>list 04</li> <li>list 05</li> <li>list 06</li> </ul> </body> </html>
Demo:
Khi sử dụng .each(), phương thức hover() sẽ chỉ tác động lên từng phần tử riêng lẻ (hover lên từng phần tử li để thấy kết quả).
So sánh code HTML trước và sau khi có jQuery:
Ví dụ 3
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Each3</title> <script src="https://code.jquery.com/jquery-latest.js"></script> <style> li{font-size: 30px} .over {color: red;} </style> <script> $(function(){ $('li').each(function(){ $(this).hover(function(){ $(this).addClass("over"); },function(){ $(this).removeClass("over"); }); if ($(this).is("#stop")){ return false; } }); }); </script> </head> <body> <h3>Di chuyển chuột vào các mục => Mục 05 và 06 không đổi màu</h3> <ul> <li>list 01</li> <li>list 02</li> <li>list 03</li> <li id="stop">list 04</li> <li>list 05</li> <li>list 06</li> </ul> </body> </html>
Demo:
Sử dụng return false; tại vị trí <li id="stop"> (sử dụng hàm is()) sẽ làm dừng không xử lý các hành động từ thành phần #stop trở đi.