gpt4 book ai didi

javascript - jquery 改变 src 属性结束

转载 作者:行者123 更新时间:2023-11-30 07:26:17 25 4
gpt4 key购买 nike

好的,所以我正在尝试在两个图像之间切换。一个是动画 gif,另一个是 jpg。基本上,客户想要大量这些关于他的产品功能的动画 gif,但我想添加一个开关来打开和关闭它,因为它真的很忙。所以,我想知道如果我有一个类的所有图像,我是否可以设置一个切换以将所有图像的最后三个字符从 gif 更改为 jpg,因为 src 的所有其余部分都会不同。

这显然行不通,但我希望你能遵循这个逻辑。

$('img.img-toggle').click(function() {
if () //If the image ends in .jpg
{
//Somehow strip the attribute of .jpg
//Somehow append the attribute to add .gif
} else {
//Somehow stip the attribute of .gif
//Somehow append the attribute to add .jpg
}
});​

有什么建议吗?如果我的逻辑很愚蠢,另一种选择也不错。我对此很陌生。我尝试了一些不同的东西,但无法弄清楚。

提前致谢,凯文

最佳答案

我们可以从图像 src string 中获取最后三个或四个字符并进行比较。

$('img.img-toggle').click(function() {
var ending = this.src.slice( -3 );

switch( ending ) {
case 'jpg':
this.src = this.src.replace( /jpg$/, 'gif' );
break;
case 'gif':
this.src = this.src.replace( /gif$/, 'jpg' );
break;
}
});

我使用了 switch/case 以防将来可能有更多格式。

另一种选择是以类似的方式使用 jQuerys .toggle() 方法

$('img.img-toggle').toggle(function() {
this.src = this.src.replace( /jpg$/, 'gif' );
}, function() {
this.src = this.src.replace( /gif$/, 'jpg' );
});

.toggle() 会自动切换你需要提供的两个函数。

关于javascript - jquery 改变 src 属性结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13976884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com