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
359 views
in Technique[技术] by (71.8m points)

javascript - change all image sources jquery

I want to change all image sources if they fail to load. Some companies block access to dropbox so I like to use an alternative link for images. Also, I don't want to modify images and css files. My code does work for the first image but makes every image source the same. How can I fix it? Thanks in advance:

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>

</head>
<body>

<img  src="img/a.png" alt="img1"/>
 <img  src="img/b.png" alt="img2"/>

</body>

<script>

var image = new Image();
image.src = "http://dropbox.com/favicon.ico";
if (image.height < 0) {

var imgsrc = $('img').attr('src');

var imgsrc1 = imgsrc.substr(imgsrc.lastIndexOf("img/"));
imgsrc1 = imgsrc.substr(4);
var imgalt = imgsrc1.substr(4,imgsrc.length - 4);

var imgsrc2 ='t/' + imgsrc1;
$('img').attr('src',imgsrc2);
$('img').attr('alt',imgalt);    

    } else {


var imgsrc = $('img').attr('src');

var imgsrc1 = imgsrc.substr(imgsrc.lastIndexOf("img/"));
imgsrc1 = imgsrc.substr(4);
var imgalt = imgsrc1.substr(4,imgsrc.length - 4);

var imgsrc2 ='http://dl.dropbox.com/u/xxxxxx/img/' + imgsrc1;
$('img').attr('src',imgsrc2);
$('img').attr('alt',imgalt);    

    }
</script>
</html>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You have to do the same procedure for all the images, I think your code only works for the first one. Specifically the line var imgsrc = $('img').attr('src');.

Try something like this inside the else-clause:

$('img').each(function() {
     var $img = $(this);
     var imgsrc = $img.attr('src');

     var imgsrc1 = imgsrc.substr(imgsrc.lastIndexOf("img/"));
     imgsrc1     = imgsrc.substr(4);
     var imgalt  = imgsrc1.substr(4,imgsrc.length - 4);

     var imgsrc2 ='http://dl.dropbox.com/u/xxxxxx/img/' + imgsrc1;
     $img.attr('src',imgsrc2);
     $img.attr('alt',imgalt);
}

It can also be noteworthy that Dropbox has a transfer limit in, at least, bandwidth per day (don't know if there is a max hit count per day though): https://www.dropbox.com/help/45


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

...