用 jQuery 动态替换图像源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11130008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:13:58  来源:igfitidea点击:

Dynamically replace image source with jQuery

jqueryreplaceimagesrcyelp

提问by David Hubler

I'm trying to replace the default Yelp star rating image for businesses with one of my own. To do so I need to find the corresponding image source for each of the possible 5 images that could have loaded. And then, based on that I need to load in the proper image I've created.

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

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

So, yelp-star-1.png would be replaced with my-star-1.png. So on and so forth. This is probably pretty simple, but I'm new to jQuery and everything I've found has not worked properly. Your expertise is very much appreciated!

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

回答by JeremyWeir

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

EDIT

编辑

I think that you're asking how to dynamically replace the src based on what is there currently. So if there is some direct difference in strings, maybe try

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

var img = $("#starRating img");
img.attr("src", img.attr("src").replace("yelp", "my"));

回答by GrayB

If you are just trying to do a basic replace without any pattern:

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

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

This could be used with images who have a src attribute starting with http://website.com/images/yelp-star-

这可以用于具有 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"));
});  

回答by Q Studio

@GrayB gave me a good solution - this does not require you to know the absolute img src:

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

jQuery('.element img').each(function() {
    jQuery(this).attr('src', jQuery(this).attr('src').replace("find_", "replace_"));
});