如果文件存在,则更改图像源 [英] Change image source if file exists

查看:115
本文介绍了如果文件存在,则更改图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 http://jsfiddle.net/rcebw/3/

重点是我将拥有大量这些 inlinediv div。每个内部都有2个div,一个用于保存图像,另一个用于保存链接。这些是从另一个站点上的子站点列表动态生成的。

The point of this is I will have numerous of these inlinediv divs. Each one has 2 divs inside it, one which holds an image and one which holds a link. These are generated dynamically from a list of the subsites on another site.

我想要它做的是检查每个div与类 inlinediv 。获取div iconLinkText 中链接的内部文本,并在站点中搜索具有该名称的文件。 ( http://www.mojopin.co.uk/images/ 进行此测试。)如果它存在然后将图像src更改为它。

What I want it to do is check each div with the class inlinediv. Get the inner text of the link in div iconLinkText and search for a file with that name at the site. (http://www.mojopin.co.uk/images/ for this test.) If it exists then change the image src to it.

我可能采取了绝对错误的路线,但我似乎无法让它工作。测试时甚至找不到 inlinediv div!说它是空的。

I am probably taking the absolutely wrong route for this but I can't seem to get it to work. When testing it can't even find the inlinediv div! Says it's null.

我对jQuery很新,但有人有任何建议吗? (我甚至不知道我是否已经解释得很好!)

I'm pretty new to jQuery but does anyone have any advice? (I don't even know if I've explained myself well!)

推荐答案

你不必使用AJAX来这样做,因为您可以没有任何限制地热链接来自其他域的图像。以下是检查图像是否存在的方法:

You don't have to use AJAX to do this, since you can hot-link images from other domains without any restrictions. Here's how you can check if an image exists:

function checkImage(src) {
  var img = new Image();
  img.onload = function() {
    // code to set the src on success
  };
  img.onerror = function() {
    // doesn't exist or error loading
  };

  img.src = src; // fires off loading of image
}

这是一个有效的实现 http://jsfiddle.net/jeeah/

这篇关于如果文件存在,则更改图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆