我有一些图片,比如
<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 元素的 src
或 id
,您可以直接更改属性,即 this .src = 'something.jpg
或 this.id = 'new_id'
。
关于javascript - jQuery - 在 jQuery.ajax().done() 中更新点击图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095798/