【问题标题】:Dynamically replace img src attribute with jQuery用 jQuery 动态替换 img src 属性
【发布时间】:2011-11-19 16:46:55
【问题描述】:

我正在尝试使用 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">

等等。

那么,我该如何替换图片:如果 img src="http://example.com/smith.gif" 然后显示 "http://example.com/williams.gif"。强>等等……

非常感谢

【问题讨论】:

  • 您在 HTML 示例中缺少关闭 "s
  • 您使用$(img) 来检查属性,并使用$(this) 来设置它。这真的是你的想法吗?
  • 这不是attr() 的工作方式。您需要使用.each() 浏览每张图片
  • 对不起,我只是快速输入解释
  • 我认为您需要更多类似的东西。 $("img[src=example.com/smith.gif]")

标签: javascript jquery image


【解决方案1】:

在我的情况下,我使用以下方式替换了 src taq:

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

【讨论】:

    【解决方案2】:

    您需要查看 jQuery 文档中的 attr 方法。你在滥用它。您在 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,则代码更少。
    【解决方案3】:

    这就是你想做的:

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

    【讨论】:

    • 谢谢先生。这就是我一直在寻找的。给我 10 分钟的时间来回答你的问题。
    猜你喜欢
    • 2012-11-16
    • 2012-07-14
    • 1970-01-01
    • 2012-01-12
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多