select the same id with different numbering jQuery

3

I use append to create numbering:

$("#navigation").append("<li class='waves-effect' id='page_" + (i + 1) + "'>" + "<a>" + (i + 1) + "</a></li>");

below I have specific css for each page number:

        $("#page_1").addClass('at')
        $("#page_2").addClass('at')
        $("#page_3").addClass('at')
        $("#page_4").addClass('ap')
        $("#page_5").addClass('ap')
        $("#page_6").addClass('ts')
        $("#page_7").addClass('tc')

Does anyone know how to make this more dynamic with the same operation? How do I select # page_1, # page_2 etc ...? Thank you

    
asked by anonymous 04.10.2016 / 12:28

2 answers

3

If it is to make it more dynamic with the same function you can create an object with the key = id page and class value of the page and go through a for creating the li. and then perform the insertion.

In addition to keeping track of only the object you gain more performance by not updating the DOM every time you use append.

var page = {
  1: "at",
  2: "at",
  3: "at",
  4: "ap",
  5: "ap",
  6: "ts",
  7: "tc"
};

var li = "";
var max = Object.keys(page).length;

for (i = 1; i <= max; i++) {
  li += "<li  class='waves-effect " + page[i] + "' id=page_" + i + ">" + i + "</li>";
}

$('#navigation').append(li);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><nav><ulid="navigation">

  </ul>
</nav>
    
04.10.2016 / 13:33
2

You can go through all elements returned by a query with .each (), see how:

$('.waves-effect').each(function(){ //passa por todos os elementos com 'waves-effect'

    //$(this) vai corresponder ao elemento atual

    var n;
    var targetClass;

    n = $(this).attr('id').replace('page_',''); //pegamos o número dentro da id
    n = parseInt(n); //convertemos de string para número

    //aqui você pode implementar a lógica de definição das classes
    if(n <= 3)
        targetClass = 'at'
    else if(n> 3 && n < 5)
        targetClass = 'ap'
    else if(n == 6)
        targetClass = 'ts'
    else
        targetClass = 'tc'


    $(this).addClass( targetClass );

});

Still the logic got a little big, to solve this it is better to see if it is possible to simplify class distribution.

    
04.10.2016 / 13:26