2013-02-20 26 views
1

我打電話這樣的功能:的Javascript:更改SRC不工作

<img src="/images/icons/info.png" 
width="18" height="18" class="iconbutton" alt="Add to Library" 
onclick="AddLibrary(12345,this.id); this.onclick=null;" /> 

功能再上崗12345到另一個腳本,然後應該更改圖標圖像:

function AddLibrary(pibnval,thisid) { 
    $.post('/addlibrary.php', { 
     pibn: pibnval 
    }, function() { 
    thisid.setAttribute('src', "/images/icons/tick.png"); 
    }); 
}; 

POST的效果很好,但圖像不會改變。

我也試過: document.getElementById(thisid).src = "/images/icons/tick.png"; 但這也沒有工作。

任何想法?

+0

哪裏是的'id'您你傳遞給函數的'img'標籤? – 2013-02-20 09:55:38

+0

你應該爲你的圖像設置一個ID。 – jbl 2013-02-20 09:56:03

+0

@jbl:不需要,它不用於任何事情。 – 2013-02-20 09:57:39

回答

5

thisid只是一個字符串,而不是一個元素。更改onclick到:

onclick="AddLibrary(12345,this); this.onclick=null;" 

(我刪除了.id)和你的thisid變量名img或一些這樣的(只所以它不是誤導):

function AddLibrary(pibnval,img) { 
    $.post('/addlibrary.php', { 
     pibn: pibnval 
    }, function() { 
    img.setAttribute('src', "/images/icons/tick.png"); 
    }); 
}; 

其他說明:

  1. 沒有理由爲此使用setAttribute,圖像元素具有src屬性。

  2. 函數聲明後不要放;

  3. 一致的縮進可以幫助您和其他人讀取您的代碼。

所以:

function AddLibrary(pibnval,img) { 
    $.post('/addlibrary.php', { 
     pibn: pibnval 
    }, function() { 
     img.src = "/images/icons/tick.png"; 
    }); 
} 
+0

美麗,謝謝! – Alasdair 2013-02-20 10:01:17

0

試試這個 - $( '#' + thisid).attr( 「src」 用戶, '/images/icons/tick.png');

此外,您的圖片必須是圖片嗎?因爲你可以與背景圖像使之股利,並設置其在CSS的寬度和高度則只是改變CSS背景這樣

$('#'+ thisid).css({'background':'/images/icons/tick.png'}); 
0

我寧願用JS(而非內聯),但你裝上處理器可以改變的代碼如下:

HTML

<img src="/images/icons/info.png" 
width="18" height="18" class="iconbutton" alt="Add to Library" 
onclick="AddLibrary(event, 12345);" /> 

JS

function AddLibrary(e, pibnval) { 
    var _this = e.target; 

    $.post('/addlibrary.php', { 
     pibn: pibnval 
    }, function() { 
     _this.setAttribute('src', "/images/icons/tick.png"); 
     _this.onclick = null; 
    }); 
}