使用jquery更改动态加载图像的src [英] Changing src of dynamically loaded images with jquery

查看:480
本文介绍了使用jquery更改动态加载图像的src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态加载一个或多个图像的div。最初,所有这些图像都是作物。目标是,当用户点击裁剪图像时,其src将被全尺寸版本替换。单击完整大小的版本以返回到裁剪的图像。我不知道图像的文件名,除了它们都是数字,除了完整版本有一个L作为文件名中的第一个字符。

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);
   }
});

我只能通过这段代码克服的问题是,如果我只是得到了img src并添加了一个'L',在第一次点击之后,img src被改为'/images/L123345.jpg'之类的东西,所以再次点击它以回到原来的src('/ images12345.jpg ')刚刚添加了第二个L.

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.

推荐答案

当您可以为图像添加其他属性时,一个选项是将基本图像文件名存储在要么是 id ,要么是 数据 - * 属性如果您使用的是HTML5。
图片如

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">

以下函数将构建一个新的 src 从当前值交换大小所需的属性。它首先检索ID,然后定义变量 lg ,如果当前源包含'L',则为空字符串,并且否则等于'L'。最后,它将两者连在一起,以及路径和文件扩展名。

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');
});

这篇关于使用jquery更改动态加载图像的src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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