Javascript:更改 src 不起作用

标签 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;" />

函数然后将 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");
    });
};

其他说明:

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

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

  3. 一致的缩进有助于您和其他人阅读您的代码。

所以:

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/

相关文章:

javascript - 如何读取图像 blob url 或将其转换为图像?

javascript - 如何在html页面中显示xml数据?

javascript - React - 开发和生产中的环境变量

JavaScript 错误 "Cannot read property"

javascript - jquery/js/html 叠加按钮

javascript - 从 lodash fill 与常规数组填充数组时出现不良结果

php - ajax发布问题

jquery - 带有图例和饼图标签的 Flot 饼图

jquery - Kendo UI 下拉列表在更改边框颜色时丢失数据

javascript - jQuery 单击事件不会在 'loaded' html 上触发