用jQuery动态替换img src属性

jQu*_*ast 31 javascript jquery image

我试图用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');
            }
Run Code Online (Sandbox Code Playgroud)

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

<img src="http://example.com/smith.gif">
<img src="http://example.com/williams.gif">
<img src="http://example.com/chris.gif">
Run Code Online (Sandbox Code Playgroud)

等等

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

非常感谢

Nik*_*iko 70

这就是你想做的事情:

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

  • 谢谢你,先生.这就是我想要的.给我10分钟回答你的问题. (4认同)

Tre*_*vor 20

您需要查看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');
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 5

就我而言,我使用以下命令替换了 src taq:

   $('#gmap_canvas').attr('src', newSrc);
Run Code Online (Sandbox Code Playgroud)