select the same id with different numbering jQuery

Asked

Viewed 297 times

3

Use append to create numbering:

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

I have specific css for each pagination number below:

        $("#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 it more dynamic with the same operation? How do I select #page_1, #page_2 etc...? Thanks

  • What is the criterion for determining the classes?

2 answers

3

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

In addition to keeping control only on the object you gain more performance by not updating the DOM every time you use the 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>
  <ul id="navigation">

  </ul>
</nav>

2

You can go through all the 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 became a little large, to solve this it is better to see if it is possible to simplify the distribution of classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.