2011-09-18 254 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