Change all jquery image sources

I want to change all image sources if they do not load. Some companies block access to Dropbox, so I like to use an alternative link for images. In addition, I do not want to modify images and css files. My code does work for the first image, but makes each image source the same. How can i fix this? 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> 
+4
source share
2 answers

You should do the same procedure for all images, I think your code only works for the first. In particular, the string var imgsrc = $('img').attr('src'); .

Try something similar inside 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 noted that Dropbox has a transmission limit of at least bandwidth per day (I don’t know if there is a maximum number of hits per day): https://www.dropbox.com/help/45

+7
source

Try the following:

 $(document).ready(function(){ $('img').each(function(){ var imgsrc = $(this).attr('src'); $(this).load(function(){ if( $(this).prop('complete') ){ 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 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); } }); } }); 
0
source

Source: https://habr.com/ru/post/1393333/


All Articles