2011-09-18 255 views
24

我想用jQuery替换给定源的img源。例如,当图像src是smith.gif时,请替换为johnson.gif。如果williams.gif替换为brown.gif等用jQuery动态替换img src属性

编辑:图像从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://例子.COM/williams.gif”。等等

非常感谢

+2

那么,什么是你的问题? – Jon

+2

你错过了在你的HTML例子中关闭''' –

+2

你正在使用'$(img)'来检查属性,'$(this)'来设置它。这真的是你想要做的吗? ?' –

回答

55

这是你想做的事:

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

谢谢你,先生,这就是我要找的,给我10分钟回答你的问题 – jQuerybeast

17

您需要在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'); 
    } 
}); 
+0

谢谢先生,我将用Niko的例子。如果你不使用var OldSrc和newSrc,代码会减少。 – jQuerybeast