Javascript jQuery-更新jQuery.ajax().done()中单击的图像
我有一些图像,比如Javascript jQuery-更新jQuery.ajax().done()中单击的图像,javascript,jquery,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=
<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" />
现在我不知道如何前进。我想在done()
调用中更改单击的图像的src
属性,但是$(this)不能确定返回单击的图像,因为$(this)。attr('id')
根据警报()
是未定义的
有人能帮我吗?那是因为这个在done
的上下文中并不是指img
。您需要在单击事件处理程序中保存上下文:
$('.unstarred-button').click(function() {
var that = this;
var id = this.id.replace(/^unstarred-/, '');
var url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
that.src = 'some/new/src.jpg';
});
});
$('.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\u id'
$('.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');
});
});