用 jQuery 动态替换 img src 属性

IT技术 javascript jquery image
2021-03-17 06:41:54

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

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

这是我尝试过的:

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');
            }

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

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

等等。

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

非常感谢

3个回答

这就是你想要做的:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
谢谢你,先生。这就是我一直在寻找的。给我10分钟回答你的问题。
2021-05-01 06:41:54

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

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

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

例子:

$('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');
  }
});
谢谢你,先生。我将使用 Niko 的例子。如果您不使用 var OldSrc 和 newSrc,则代码更少。
2021-04-27 06:41:54

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

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