我希望能够对一组div依次应用三种颜色(红色、绿色和蓝色)。我使用数组和“for”循环来对div应用颜色,但是它并不能正常工作。
我的代码如下:
$(document).ready(function(e) {
var colors = ["red", "green", "blue"];
var len = $('.box').length;
for (var j = 0; j < len; j++) {
$(this).find('.box').addClass(colors[j]);
}
});
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.box {
float: left;
height: 50px;
margin-left: 5px;
margin-top: 10px;
width: 50px;
border: 1px solid #000;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</body>
</html>