Javascript:更改src无法正常工作

Ala*_*air 1 javascript jquery

我正在调用这样的函数:

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

然后该函数将POSTS 12345转移到另一个脚本,然后应该更改图标图像:

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

POST效果很好,但图像不会改变.

我也试过了, document.getElementById(thisid).src = "/images/icons/tick.png"; 但那也没用.

有任何想法吗?

T.J*_*der 5

thisid只是一个字符串,而不是一个元素.将您更改onclick为:

onclick="AddLibrary(12345,this); this.onclick=null;"
Run Code Online (Sandbox Code Playgroud)

(我删除了.id)和你的thisid变量名称img或其他一些(只是因为它没有误导性):

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

其他说明:

  1. 没有理由使用setAttribute它,图像元素具有src属性.

  2. 你不要放在;函数声明之后.

  3. 一致的缩进可以帮助您和其他人阅读您的代码.

所以:

function AddLibrary(pibnval,img) {
    $.post('/addlibrary.php', {
        pibn: pibnval
    }, function() {
        img.src = "/images/icons/tick.png";
    });
}
Run Code Online (Sandbox Code Playgroud)