使用 jQuery 将目录附加到图像源

Prepend directory to image source with jQuery

本文关键字:图像 jQuery 使用      更新时间:2023-09-26

我的网站上有 5 行,每行都有一个图像。

单击时,图像的大小会增加,但id随后希望将目录附加到图像源,以便它成为不同的图像。

这在jQuery中可能吗?

现在

<img src="image.jpg" />

我想要什么

<img src="hires/image.jpg" />

我读过有关使用"数据源"标签的信息,但我似乎无法正常工作?

$('img').click(function(){
    $(this).attr({'src'}).prepend('hires');
});

这是你要找的吗?

$('img').click(function(){
    $(this).attr('src', function(i, value) {
        return 'hires/' + value;
    });
});

不过,它会在每次点击时预先附加hires/。您可以使用.indexOf测试它是否已经存在:

$(this).attr('src', function(i, value) {
    return value.indexOf('hires/') === -1 ?  'hires/' + value : value;
});

如果要在 hires/hires/ 之间切换,请删除字符串(如果存在(:

$(this).attr('src', function(i, value) {
    return value.indexOf('hires/') === -1 ?  
        'hires/' + value : 
        value.replace('hires/', '');
});

.prepend 是一个添加 DOM 元素的 jQuery 方法。它不是本机字符串方法。此外,那里的大括号是错误的(语法错误(。

这应该可以做到:

$('img').click(function(){
    var imgSRC = $(this).attr('src');
    $(this).attr('src', 'hires/' + imgSRC);
  });

你可以这样做,

现场演示

$('img').click(function(){
    $(this).attr('src', function(i, value) {
        return 'hires/' + value;
    });   
});
$(this).attr({'src'}).prepend('hires');

上面一行有几点错误。

{'src'}是一个SyntaxtError.在 JavaScript 中,大括号用于创建新对象(或新代码块(。对象由键值对组成,例如

var obj = { aKey: 42 };
obj.aKey // 42

更新。从 ES2015 开始,如果存在与键同名的变量,并且可以在创建对象的范围内访问,则可以省略该值。

var aKey = 42;
var obj = { aKey }; // Note, there're no quotes
obj.aKey // 42

$.fn.attr 既可以作为getter工作,也可以根据它收到的参数作为setter。您可能希望将其用作获取当前src属性$(this).attr('src')$(this).attr('src', 'something')更新它。

$.fn.prepend 不适用于字符串。它用于将内容插入到每个匹配元素的开头。

所以最后这是实现目标的正确方法:

$(this).attr('src', 'hires/' + $(this).attr('src'));
$(this).attr('src', "hires/" + $(this).attr('src'));