我的网站右侧有很多社交按钮( <img>
中的 <ul>
)。
它们的文件名可能类似于 google.png
, 或 twitter.png
.
我现在想更改 src
悬停在 google_b.png
或 twitter_b.png
- 我将始终以这种方式为所有文件命名我的文件。
我的问题是如何轻松地将文件名更改为 _b
(保留文件扩展名)而不必预定义文件名?
目前我的代码是这样的:
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src');
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src');
// remove _b to make it img.png again
$img.attr('src', src);
});
最佳答案
假设文件不会有伪造的扩展名 (image.png.jpeg
) 只需在 .
上拆分 src,将 _b
添加到第二个到最后一部分并在 .
.
src = $img.attr('src');
var temp = src.split(".");
temp[temp.length - 2] += "_b"; //change second to last element of array
src = temp.join(".");
关于javascript - 使用 JS/jQuery 修改路径的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806203/