Javascript 用 jQuery 动态替换 img src 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7462119/
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-24 02:23:30  来源:igfitidea点击:

Dynamically replace img src attribute with jQuery

javascriptjqueryimage

提问by jQuerybeast

I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.gif etc.

我正在尝试使用 jQuery 替换给定源的 img 源。例如,当图像 src 为 smith.gif 时,替换为 johnson.gif。如果 williams.gif 替换为 brown.gif 等。

EDIT: The images are retrieved from an XML to a random order, without class to each .

编辑:图像从 XML 检索到随机顺序,每个 .

This is what I tried:

这是我尝试过的:

if ( $("img").attr('src', 'http://example.com/smith.gif') ) {
              $(this).attr('src', 'http://example.com/johnson.gif');
            }
if ( $("img").attr('src', 'http://example.com/williams.gif') ) {
              $(this).attr('src', 'http://example.com/brown.gif');
            }

Note that my HTML has many images. For example

请注意,我的 HTML 有很多图像。例如

<img src="http://example.com/smith.gif">
<img src="http://example.com/williams.gif">
<img src="http://example.com/chris.gif">

etc.

等等。

So, how can I replace the images: IF img src="http://example.com/smith.gif" then show "http://example.com/williams.gif".etc...

那么,如何替换图像:IF img src="http://example.com/smith.gif" 然后显示“http://example.com/williams.gif”。等等...

Thanks alot

非常感谢

回答by Niko

This is what you wanna do:

这就是你想要做的:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

回答by Trevor

You need to check out the attrmethod in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags srcwith the string specified in the 2nd parameter.

您需要查看attrjQuery 文档中的方法。你在滥用它。您在 if 语句中所做的只是将所有图像标记替换src为第二个参数中指定的字符串。

http://api.jquery.com/attr/

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

替换一系列图像源的更好方法是循环遍历每个图像并检查其源。

Example:

例子:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

回答by Primoshenko

In my case, I replaced the src taq using:

就我而言,我使用以下方法替换了 src taq:

   $('#gmap_canvas').attr('src', newSrc);