Changing src of dynamically loaded images with jqu

2019-08-31 06:08发布

I have a div that is loaded dynamically with one or more images. Initially, all these images are crops. The aim is, when a when a user clicks on a cropped image, its src is replaced by the full sized version. Click the full sized version to return to the cropped image. I have no knowledge of the file names of the image, other than that they are all numbers, except the full version has a "L" as the first character in the file name.

This code works, but I'm sure there must be a simpler way:

$('#class').on('click', '> img', function() {
var src = $(this).attr('src');
var test_src = src.match(/L/g);
var img_id = src.replace(/L/g, '');
var big_img = src.replace('/images/', '/images/L');
if (test_src == undefined) {
  $(this).attr('src', big_img)
    } else {
  $(this).attr('src', img_id);
   }
});

The problem I only managed to overcome with this code was, if I simply got the img src and added an 'L', after the first click, the img src was changed to something like '/images/L123345.jpg', and so, clicking it again with the aim of returning to the original src ('/images/12345.jpg') just added a second L.

I'm sure I've missed something really obvious. Thanks for any suggestions.

标签: jquery image src
3条回答
老娘就宠你
2楼-- · 2019-08-31 06:56

When you can add other attributes to your images, one option is to store the base image filenames in either the id, or in a data-* attribute if you're using HTML5. With images such as

<img src="/images/1234.jpg" class="class" data-id="1234">
<img src="/images/L5678.jpg" class="class" data-id="5678">

the following function will build a new src attribute required to swap the size from its current value. It does this first by retrieving the ID, then defining a variable lg that is an empty string if the current source includes an 'L', and equal to 'L' otherwise. Finally, it strings the two together, along with the path and file extension.

$('.class').on('click', '> img', function() {
    var id = $(this).attr('data-id');
    var lg = ($(this).attr('src').match(/L/) !== null) ? '' : 'L';
    $(this).attr('src', '/images/' + lg + id + '.jpg');
});
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-31 07:03

You could try using jQuery class methods. Not sure if it's simpler, but I find it easier to read.

$('#class').on('click', '> img', function() {
  var src = $(this).attr('src');
  if ($(this).hasClass('small')) {
    src.replace('/images/', '/images/L');
    $(this).removeClass('small');
    $(this).addClass('large');
  }
  else if ($(this).hasClass('large')) {
    src.replace('/images/L', '/images/');
    $(this).removeClass('large');
    $(this).addClass('small');
  }
  $(this).attr('src', src);

});
查看更多
仙女界的扛把子
4楼-- · 2019-08-31 07:09

This might work...

var $img = $("<img>");

$img.on('load', function (e) {
    this.$photoImageManager.attr('src', e.target.src);
}.bind(this));

$img.attr('src', "../../users/" + userId + "/" + userId + "-photo.png");
查看更多
登录 后发表回答