Định nghĩa .each() trong jquery

.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ấu trúc

Đã được thêm vào từ phiên bản 1.0

.each(function(){}

 $("li").each(function(index){
      $(this).addClass("list"+index);
    });

.each(function(){}

Code Html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#target").click(function(){
    $("li").each(function(index){
      $(this).addClass("list"+index);
    });
  });
});
</script>
<style>
.list0 { color: red; }
.list1 { color: blue; }
.list2 { color: yellow; }
.list3 { color: green; }
.list4 { color: gray; }
.list5 { color: pink; }
</style>
</head>
<body>
<div style="background: #ecf9f9;border-radius: 4px; border: 1px solid #ddd; margin: 5px 0; padding: 10px;word-wrap: break-word;">
<div style="background: #fff; border: 1px dashed #ddd; margin: 5px; padding: 10px;">
<button id="target">click đổi màu</button>
<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>
</div></div>
</body>
</html>

Kết quả:

Viết câu trả lời

Drop Images

0 Bình luận