Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda