Love beautiful code? We do too.
.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 thêm vào từ phiên bản 1.0
.each(function(){}
-------------------------------------------------------------------------------------------
$('li').each(function(index){
$(this).click(function(){
$(this).addClass("test"+index);
});
});
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.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>
<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>
Hiển thị trình duyệt:
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ả).
Hoclaptrinh.vn © 2017
From Coder With
Unpublished comment
Viết câu trả lời