如何选择父div和amp;中的每个div?使用增加的索引号应用类(om_0&继续)。在这里,我无法定位每个div。
或者如何向每个div添加属性id =“om_0”,id =“om_1”,id =“om_2”等
问题在于它将所有类应用于一个div&重复一遍
var cirLength = $("div#circleBox > div").length;
for(var i=0; i<cirLength; i++){
$("div#circleBox").find('div').addClass('om_'+i);
}
<div id="circleBox"><div class="om_0 om_1 om_2"><span>AcessGreen</span></div><div class="om_0 om_1 om_2"><span>AccessBlue</span></div><div class="om_0 om_1 om_2"><span>AccessOrange</span></div></div>
答案 0 :(得分:0)
您可以使用 each()
来迭代jQuery对象
$("div#circleBox").find('div').each(function(i) {
$(this).addClass('om_' + i);
// If you need to add it as id then use `this.id= 'om_' + i ` instead of `$(this).addClass('om_' + i)`
});
&#13;
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>
&#13;
使用您自己的代码,您需要使用 eq()
var cirLength = $("div#circleBox > div").length;
for (var i = 0; i < cirLength; i++) {
$("div#circleBox").find('div').eq(i).addClass('om_' + i);
}
&#13;
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>
&#13;