我正在调用这样的函数:
<img src="/images/icons/info.png"
width="18" height="18" class="iconbutton" alt="Add to Library"
onclick="AddLibrary(12345,this.id); this.onclick=null;" />
函数然后将 POSTS 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";
但这也不起作用。
有什么想法吗?
最佳答案
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");
});
};
其他说明:
没有理由为此使用
setAttribute
,图像元素具有src
属性。不要在函数声明之后放置
;
。一致的缩进有助于您和其他人阅读您的代码。
所以:
function AddLibrary(pibnval,img) {
$.post('/addlibrary.php', {
pibn: pibnval
}, function() {
img.src = "/images/icons/tick.png";
});
}
关于Javascript:更改 src 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14976856/