简体   繁体   English

检查图片是否存在于Javascript中

[英]Check to see if an image exists in Javascript

I'm a beginning html/javascript programmer and I'm making a basic page that displays my images. 我是一名初学者html / javascript程序员,正在制作一个显示我的图像的基本页面。 The images are already numbered(starting at 000), so I made an iterator that ups the number every time through the while loop. 图像已经编号(从000开始),因此我进行了迭代,每次通过while循环都增加了编号。 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. 我对如何使用Ajax或jQuery几乎一无所知,如果需要它们,请让我知道如何添加它们。

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." 我尝试使用SE和ajax的代码片段从一个文件夹中提取所有图像(超级整洁),但出现错误:“未定义$。” Which is why I'm trying this. 这就是为什么我要这样做。

EDIT: removed uncalled xhtml function. 编辑:删除了未调用的xhtml函数。

EDIT: re-added and called xhtml function. 编辑:重新添加并称为xhtml函数。 that cIter function now looks as follows: 该cIter函数现在如下所示:

    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. 它可以工作,但是却给我带来以下错误:不赞成在主线程上使用同步XMLHttpRequest,因为它对最终用户的体验有不利影响。 For more help http://xhr.spec.whatwg.org not well-formed NS_ERROR_DOM_BAD_URI: Access to restricted URI denied 有关更多帮助, http ://xhr.spec.whatwg.org格式不正确的NS_ERROR_DOM_BAD_URI:拒绝访问受限制的URI

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. 提示epascarello指出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM