Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - Change image source if file exists

I have http://jsfiddle.net/rcebw/3/

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.

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

Here's a working implementation http://jsfiddle.net/jeeah/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...