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
6 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - Skip numbers while doing a For loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744769696a2624263.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论