7

我正在尝试用我自己的一张图片替换默认的 Yelp 星级图片。为此,我需要为可能已加载的 5 个图像中的每一个找到相应的图像源。然后,基于此,我需要加载我创建的正确图像。

<div id="starRating">
    <img src="http://yelp-star-1.png"/>
</div>

因此,yelp-star-1.png 将被替换为 my-star-1.png。等等等等。这可能很简单,但我是 jQuery 新手,我发现的所有东西都不能正常工作。非常感谢您的专业知识!

4

3 回答 3

14
$("#starRating img").attr("src", "http://pathto/my-star-1.png")

编辑

我认为您是在询问如何根据当前的内容动态替换 src 。所以如果字符串有一些直接的区别,也许试试

var img = $("#starRating img");
img.attr("src", img.attr("src").replace("yelp", "my"));
于 2012-06-21T00:27:42.760 回答
5

如果您只是尝试在没有任何模式的情况下进行基本替换:

$('img[src="http://website.com/images/yelp-star-1.png"]').attr('src','http://website.com/images/my-star-1.png');

这可以用于具有 src 属性以开头的图像http://website.com/images/yelp-star-

$('img[src^="http://website.com/images/yelp-star-"]').each(function() {
   $(this).attr('src', $(this).attr('src').replace("yelp", "my"));
});  
于 2012-06-21T00:41:38.833 回答
4

@GrayB 给了我一个很好的解决方案——这不需要你知道绝对的 img src:

jQuery('.element img').each(function() {
    jQuery(this).attr('src', jQuery(this).attr('src').replace("find_", "replace_"));
}); 
于 2013-10-12T15:32:25.183 回答