admin管理员组

文章数量:1391798

I have 80 div with unique ids that counts from 0 to 80,e.g. grid0, grid1, grid2 and so on.

I want to use a for loop to iterate over all of them and hide them,but I want to skip some grids. What should I do?

This an inaccurate example of what I mean:

for ( var i = 0; i <= 80; i++) (skip numbers 51,60,69,78) {
  $("grid" + i).hide();
}

I have 80 div with unique ids that counts from 0 to 80,e.g. grid0, grid1, grid2 and so on.

I want to use a for loop to iterate over all of them and hide them,but I want to skip some grids. What should I do?

This an inaccurate example of what I mean:

for ( var i = 0; i <= 80; i++) (skip numbers 51,60,69,78) {
  $("grid" + i).hide();
}
Share Improve this question edited Mar 27, 2017 at 16:33 PMA asked Mar 27, 2017 at 15:59 PMAPMA 892 silver badges14 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 2

You could make a check with Array#indexOf,

for (var i = 0; i <= 80; i++) {
    if ([51, 60, 69, 78].indexOf(i) === -1) {
        $("grid" + i).hide();
    }
}

or with ES6 and Array#includes

for (var i = 0; i <= 80; i++) {
    if (![51, 60, 69, 78].includes(i)) {
        $("grid" + i).hide();
    }
}

BTW, your string building method does not work, you need to put plus sign and index outside of the string.

$("grid" + i).hide();
//^^^^^          string
//       ^       concatination
//         ^     with number
for ( var i = 0; i <= 80; i++) {
  if (![51,60,69,78].includes(i))
    $("grid" + i).hide();
}

You are looking for the continue JavaScript keyword.

for ( var i = 0; i <= 80; i++) {

    if(i === 51
    || i === 60
    || i === 69
    || i === 78) {

        continue;

    }

  $("grid+ i").hide();

}

https://www.w3schools./js/js_break.asp

The continue statement "jumps over" one iteration in the loop.

So inside your loop just do an if (i == 51) continue before the hide

Give the elements a class, hide all of them via class and then show the ones you need:

<div class="grids" id="grid0"></div>
<div class="grids" id="grid1"></div>
<div class="grids" id="grid2"></div>
...

$("div.grids").hide();
$("#grid51").show();
$("#grid60").show();
for ( var i = 0; i <= 80; i++){
   if(i !==51 && i !== 60 && i !== 69 && i !== 78){
      $("grid+ i").hide();
   }


}

本文标签: javascriptSkip numbers while doing a For loopStack Overflow