Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用jQuery动态替换img src属性_Javascript_Jquery_Image - Fatal编程技术网

Javascript 用jQuery动态替换img src属性

Javascript 用jQuery动态替换img src属性,javascript,jquery,image,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.g

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


非常感谢

这就是你想要做的:

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

您需要检查jQuery文档中的
attr
方法。你误用了它。if语句中的操作只是用第2个参数中指定的字符串替换所有图像标记
src

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

示例:

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

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


$('gmap_canvas').attr('src',newSrc)
您在HTML示例中缺少关闭
s您使用
$(img)
检查属性,使用
$(this)
设置属性。这真的是您想做的吗?这不是
attr()
的工作方式。您需要使用
。each()浏览每个图像
对不起,我刚刚快速输入了解释,我想您需要类似的解释。$(“img[src=)谢谢您,先生。这就是我要找的。请给我10分钟时间回答您的问题。谢谢您,先生。我将使用Niko的示例。如果您不使用var OldSrc和newSrc,请减少代码。