我目前在HTML元素中添加了一个属性,如下所示。我正在尝试将类添加到第n个元素。例如.project
的{{1}}为1,4,7 ...将添加类data-project-id
和2,5,8 ...将添加类.project-group-1
等...
.project-group-2
是否有任何jQuery助手可以实现这一目标?
答案 0 :(得分:2)
试试这个:
$(function() {
$('.project').each(function() {
var groups = 3;
var group = parseInt($(this).data('project-id')) % groups;
$(this).addClass('project-group-' + (group == 0 ? groups : group));
});
});
您可以在行动here中查看。
答案 1 :(得分:0)
$(function(){
var count =1;
$( ".project" ).each(function() {
var project_id = $(this).attr("data-project-id");
if(project_id != "undefined"){
if(count == 1) {
$(this).addClass("project-group-"+project_id);
}
count++;
if(count == 3)
count = 1;
}
});
});
查看Jsfiddle示例
答案 2 :(得分:0)
var nums = ["1","4","7"];
for( i in nums){
$("a[data-project-id=" + nums[i] + "]").addClass("project-group-" + nums[i]);
}
答案 3 :(得分:0)
你可以这样做:
$(".project").addClass(function () {
var groupId = this.dataset.projectId % 3 == 0 ? 3 : this.dataset.projectId % 3;
return "project-group-" + groupId;
});
.project-group-1 {
background: red;
}
.project-group-2 {
background: blue;
}
.project-group-3 {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="project" data-project-id="1" href="#">Project</a>
<a class="project" data-project-id="2" href="#">Project</a>
<a class="project" data-project-id="3" href="#">Project</a>
<a class="project" data-project-id="4" href="#">Project</a>
<a class="project" data-project-id="5" href="#">Project</a>
<a class="project" data-project-id="6" href="#">Project</a>
<a class="project" data-project-id="7" href="#">Project</a>
<a class="project" data-project-id="8" href="#">Project</a>
<a class="project" data-project-id="9" href="#">Project</a>