javascript - jQuery - 在 jQuery.ajax().done() 中更新点击图像

标签 javascript jquery

我有一些图片,比如

<img src="unstarred.png" class="unstarred-button" id="unstarred-1" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-2" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-3" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-4" />

然后我绑定(bind)这个函数:

$('.unstarred-button').click(function() {
    id = $(this).attr('id').replace(/^unstarred-/, '');
    url = '/star.php?id=' + id;

    $.ajax({
        type: 'GET',
        url:  url
    }).done(function() {
        // What should be put here?
    });
});

现在我不知道如何前进。我想在 done() 调用中更改被点击图像的 src 属性,但是 $(this) 确实不会返回被点击的图像,因为 $(this).attr('id') 根据 alert()undefined

有人能帮帮我吗?

最佳答案

那是因为 done 上下文中的 this 没有引用 img。您需要在 click 事件处理程序中保存上下文:

$('.unstarred-button').click(function() {
    var self = $(this);
    id = self.attr('id').replace(/^unstarred-/, '');
    url = '/star.php?id=' + id;

    $.ajax({
        type: 'GET',
        url:  url
    }).done(function() {
        self.attr('src', 'something.jpg');
    });
});

此外,您不需要 jQuery 来更改 DOM 元素的 srcid,您可以直接更改属性,即 this .src = 'something.jpgthis.id = 'new_id'

关于javascript - jQuery - 在 jQuery.ajax().done() 中更新点击图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095798/

相关文章:

javascript - 如果响应有效则显示 window.alert

javascript - 为什么循环后的代码在循环内 dom 更改之前执行?

javascript - 在这种情况下如何获取选定的表 tr 行

javascript - 创建 chrome 扩展以将数据发送到本地主机服务器

jquery - 我想格式化我的时间选择器 jquery

javascript - 父div之外的类的Jquery最接近方法

javascript - 我无法使平滑滚动 slider 在我的网站上工作

jquery dotdotdot 插件(添加省略号)不适用于 Bootstrap 轮播

JavaScript Pi Spigot 算法不起作用

javascript - 选择另一个选择中的选项时隐藏多重选择框中的选项