Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Reset counter in jQuery function

Ok, this seems pretty basic but I'm stuck.

I'm setting a var outside of the loop, then increment and once the counter reaches a threshold I need to reset it back to 0.

var cnt = 0;
$("ul").each(function(cnt) {
    var ths = $(this),
        tul = ths.attr("id");
        
    cnt = cnt++;
       
    if (cnt == 20) {
        cnt = 0;
    }
...
});

For some reason it keeps incrementing till the end of the look. What am I missing?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If cannot be reset to 0 because cnt is the .each(function(cnt) { function's index argument, and will always be the iterating index. You're trying to reset something to 0 which in the next loop will again be the index integer.

Depending on what's the desired (not clear from your question so far) you could simply not use the index attribute:

let cnt = 0;

$("ul").each(function() {
  cnt += 1;
       
  if (cnt === 20) {
    cnt = 0;
  }

   // ...
});

Modulo (reminder) operator

Use the reminder operator % to loop back to 0 once idx becomes 20.
In that case you don't need the outer variable, but you can use the iterating index attribute instead:

$("ul").each(function(idx) {
  const cnt = idx % 20;  // Reset to 0 once idx is 20  

   // ... 
});
about 4 years ago · Juan Pablo Isaza Relatório

0

The first argument to the function is the index of the array. Checkout the jQuery documentation. https://api.jquery.com/each/

You do not need to pass the parameter to the function. See code below.

var cnt = 0;
$("ul").each(function() {        
    cnt++;
   
    if (cnt == 20) {    
        cnt = 0;
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda