简体   繁体   中英

Add class to nth attribute with jQuery

I currently add an attribute to the HTML element like shown below. I'm trying to add a class to nth element. For example .project 's with data-project-id of 1, 4, 7... would add class .project-group-1 and 2, 5, 8... would add class .project-group-2 etc...

<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>

Is there any jQuery helpers that make this possible?

Try this:

$(function() {
    $('.project').each(function() {
        var groups = 3;
        var group = parseInt($(this).data('project-id')) % groups;
        $(this).addClass('project-group-' + (group == 0 ? groups : group));
    });
});

You can check it out in action here .

$(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;            
        }
    });
});

Look at Jsfiddle example

var nums = ["1","4","7"];
for( i in nums){
     $("a[data-project-id=" + nums[i] + "]").addClass("project-group-" + nums[i]);
}

You can do it like this:

 $(".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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM