Break loop based on element not existing

我只是一个虾纸丫 提交于 2019-12-11 16:32:32

问题


I have built a cms that allows users to add up to 10 images into the slideshow, which all output in the front end in divs with ids of showcaseSlide with a number from 0-9 appended on the end, e.g. showcaseSlide0, showcaseSlide1 etc. For the javascript that controls the slideshow, I need to output all of the div id's into an array, but end the array when the slides finish, eg if the div ids went from showcaseSlide0 - showcaseSlide3, I would need the array to go from slides[0] - slides[3].

Here is the current code and some commented out code that I have tried before:

var slides = new Array();
var count = 0;
for(i=0; i<=10; i++){
slides[i] = "showcaseSlide"+i;
document.write(slides[i]); //so that I can see which id's are in the array
var div = document.getElementById(slides[i]);
//if(div) { break; } <- doesn't break
//if(document.getElementById(slides[i]) == null) break; <-breaks after 1st
//if(document.getElementById(slides[i]) == undefined) break; <- breaks after 1st
};

Edit:

I've found out (thanks to Teemu who commented below) that it wasn't working because it was called before the page load, therefore before the objects were rendered. I also have to thank Peter Kelly (who also commented below), who pointed out that I needed to use a ! in my breaking if statement and Frazer who pointed out my loop was 1 too big.

Here is the new code (including the other elements of the initialising function):

var count = 0;
var wait = 4000;
var slides = [];

function startShowcase() {

    for(var i=0; i<10; i++){
        slides[i] = "showcaseSlide"+i;;
       if(!document.getElementById(slides[i])) { break; }
    };
    setInterval(showcase, wait);

};

回答1:


I wouldn't be so complex. I guess you have a class applied to all your slides div? If you do, use something like the following:

var slides = []
var divs = document.getElementsByClassName('slide-class')
for (var i = 0, l = divs.length; i < l; ++i) {
    slides.push("showcaseSlide" + i)
}

Btw, several comments about your code:

  • Don't use new Array(). Instead, use []. See here to understand why.
  • You didn't use the var keyword to declare your i variable, which means this variable is global. Global is evil.
  • document.write is evil.

I guess your count variable has some use later?




回答2:


You have DIVs numbered 0-9 but your loop runs 11 times.

Not actual code, but this explains it.

for(i=0; i<=10; i++){
  0 = 1st 
  1 = 2nd
  2 = 3rd
  3 = 4th
  4 = 5th
  5 = 6th
  6 = 7th
  7 = 8th
  8 = 9th
  9 = 10th
  10 = 11th
}


来源:https://stackoverflow.com/questions/9601911/break-loop-based-on-element-not-existing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!