![](/img/trans.png)
[英]Dynamically change the HTML <img> src attribute using Java Script or JQuery
[英]Dynamically replace img src attribute with jQuery
我正在嘗試使用 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">
等等。
那么,如何替換圖像: IF 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 語句中所做的只是將所有圖像標簽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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.