I'm a beginning html/javascript programmer and I'm making a basic page that displays my images. The images are already numbered(starting at 000), so I made an iterator that ups the number every time through the while loop. The problem is that I don't know how to check to see if the image that the path leads to exists. I know literally nothing about how to use Ajax or jQuery, and if they're required let me know how to go about adding them.
Here's my current code:
<script>
function printimg(url){
var img = document.createElement("img");
img.src = url;
img.align = "middle";
var src = document.getElementById("body");
src.appendChild(img);
}
//Pull all images from folder.
var cIter = 000;
imgRun =1;
while (imgRun == 1){
uIter = String(cIter);
if (uIter.length < 3){
uIter = "0" + uIter;
if (uIter.length < 3){
uIter = "0" + uIter;
}
}
cPath = ('./files/images/comics/'+uIter+'.png');
cIter ++;
printimg(cPath);
//stop printing images after the 5th one (find a better if statement)
if (cIter > 5){
imgRun = 0;
}
}
</script>
if there's a more convenient/simple/efficient way of doing this, let me know. I tried using a snippet from SE with ajax that pulled all images from a folder (which is super neat) but I got an error: "$ is not defined." Which is why I'm trying this.
EDIT: removed uncalled xhtml function.
EDIT: re-added and called xhtml function. that cIter function now looks as follows:
if (!imageExists(cPath)){
imgRun = 0;
}
else{
printimg(cPath);
}
It works, but gives me the following errors: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org not well-formed NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Of all the things, I just forgot to call my function. I'm still getting errors, but they aren't visibly effecting my page, so I suppose it's alright. Props to epascarello for pointing it out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.