Home > Mobile >  Reset counter in jQuery function
Reset counter in jQuery function

Time:05-09

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?

CodePudding user response:

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  

   // ... 
});

CodePudding user response:

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;
    }
});
  • Related