简体   繁体   English

动态图像标签

[英]Dynamic image tag

How do I create an tag that look for the image name in 10 different folders and if not found outputs a placeholder image using Javascript? 如何创建在10个不同的文件夹中查找图像名称的标签,如果找不到,则使用Javascript输出占位符图像?

Thanks. 谢谢。

var img = new Image();
img.onload = function(){ alert("I am loaded"); };
img.onerror = function(){ alert("I am not loaded"); };
img.src = "/foo/bar.gif";

If you get onerror, try setting the source again to the next image in your list. 如果出现错误,请尝试再次将源设置为列表中的下一张图像。

I would go with such script: 我会使用这样的脚本:

<script type="text/javascript">
var arrPossibleImageFolders = ["folder1", "folder2", "folder3"];
var strDefaultImage = "nopicture.gif";
function TryDifferentFolder(oImage) {
    var folderIndex = parseInt(oImage.getAttribute("folder_index"), 10);
    if (isNaN(folderIndex))
        folderIndex = 0;
    folderIndex++;
    if (folderIndex >= arrPossibleImageFolders.length) {
        oImage.src = strDefaultImage;
        return;
    }

    var lastSlashIndex = oImage.src.lastIndexOf("/");
    var strNewSource = arrPossibleImageFolders[folderIndex] + "/" + oImage.src.substr(lastSlashIndex);
    oImage.src = strNewSource;

    oImage.setAttribute("folder_index", folderIndex + "");
}
</script>

Then have such image tag to trigger the code: 然后有这样的图像标签来触发代码:

<img src="folder1/mypicture.gif" onerror="TryDifferentFolder(this);" />

This will search for "mypicture.gif" in folder1 first, then if not found (onerror triggered) will try in folder2 etc, finally loading the default picture. 这将首先在folder1搜索“ mypicture.gif”,然后如果未找到(触发了错误),则将在folder2等中尝试,最后加载默认图片。

Really, you should do something like this on the server side, where the files actually are; 确实,您应该在服务器端(实际上是文件所在的位置)执行类似的操作; make a script that looks for the image and sends what it finds. 创建一个脚本来查找图像并发送找到的图像。

(Edited to remove my original JS solution, since it was bad, and others have suggested better ones.) (编辑后删除了我原来的JS解决方案,因为它很糟糕,其他人建议使用更好的解决方案。)

Sounds like you may need to use a bunch of onerror handlers. 听起来您可能需要使用许多onerror处理程序。 Try to load some image, catch possible error till you run out of candidates. 尝试加载一些图像,捕获可能的错误,直到用尽所有候选图像。 Load placeholder as the last image. 加载占位符作为最后一个图像。

I'd solve it with Ajax, try to load each image, if you get a 200 that means the image exists, if 404 try next image. 我会用Ajax解决它,尝试加载每个图像,如果得到200表示图像存在,如果404尝试下一个图像。

var images = ['/images/1.jpg', '/images/2.jpg', '/images/3.jpg'];
var imageExists = false;
for(var i = 0; i < images.length; i++){
  if(!imageExists){
    $.ajax({
      url: images[i],
      async: false,
      success: function(){
        // use images[i] as your image
        imageExists = true;
      }
    });
  }
}
if(!imageExists) {
  // use default image
}

Since you are asking about how to do it with a tag i'll show a solution, although i'd never do it myself: 既然您正在询问如何使用标签,我将展示一个解决方案,尽管我自己也不会这样做:

<script>
urlsToTry = ['http://url2.com','http://url3.com','http://you.get.the.picture.com','http://www.google.com/images/logos/ps_logo2.png'];
</script>
<img src="http://url1.com" style="display: none;" onload="this.style.display='block';" onerror="if(urlsToTry.length) { this.src = urlsToTry.shift(); } else { alert('none of the urls worked!'); }">

You can see an example of it here: http://jsfiddle.net/LLQLH/1/ 您可以在此处查看示例: http : //jsfiddle.net/LLQLH/1/

One of the downsides to this approach is that it tries to load the picture serially which can cause quite a wait if they all fail. 这种方法的缺点之一是它尝试串行加载图片,如果它们全部失败,则可能会导致相当大的等待。 The parallel approach using proper js would be the way to go imo: 使用正确的js的并行方法将成为imo的方法:

<script>
var loadQueue={};
var urlsToTry = ['http://url1.com','http://url2.com','http://url3.com','http://you.get.the.picture.com'];

function showTag(url) {
    var tag = document.getElementById('myimage');
    if(url) tag.src = url; 
    tag.style.display='inline-block';       
}

function onLoadEventHandler(url) {
    return function() {
        delete loadQueue[url];
        for(var i = 0, img; img = loadQueue[i]; i++) {
            img.onload = null;
        }
        loadQueue = null;
        showTag(this.src);
    }
}

function onErrorEventHandler(url) { 
    return function() {
        delete loadQueue[url];
        for(var i in loadQueue) return;
        showTag(); //we will only get here if loadQueue is empty
    }
}

for(var i = 0, url; url = urlsToTry[i]; i++) {
    loadQueue[url] = new Image();
    loadQueue[url].onload = onLoadEventHandler;
    loadQueue[url].onerror = onErrorEventHandler(url);
    loadQueue[url].src = url;
}
</script>
<img id="myimage" src="http://www.google.com/images/logos/ps_logo2.png" style="display: none;">

You can see it working here: http://jsfiddle.net/DJ2SH/ 您可以在这里看到它的工作: http : //jsfiddle.net/DJ2SH/

大声笑,这不能仅使用一些标签来完成,您应该适当地使js(jquery / ajax)函数搜索该文件,然后更新img的href属性...或者您应该多说明一些意图

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

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