每当单击投票按钮时,我都会加载一个 ajax-loader gif。然而,图像会出现在所有项目中。我正在尝试找出如何只为我投票的项目加载图像。这是我的代码。
$(document).ready(function(){
$(".vote").click(function(e) {
$('.ajax_load').html('<img src="/images/ajax-loader.gif" />');
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$.ajax({
type: "POST",
url: "vote.php",
data: dataString,
cache: false,
success: function(html) {
$('.ajax_load').html('Voted!');
}
});
return false;
});
});
HTML 示例
<div class="vote" id=88">Vote</div> <div class="ajax_load">
<div class="vote" id=92">Vote</div> <div class="ajax_load">
<div class="vote" id=38">Vote</div> <div class="ajax_load">
最佳答案
从 html 样本来看,这些元素看起来像是 sibling ,所以您应该使用
$(this).nextAll('.ajax_load:first').html('<img src="/images/ajax-loader.gif" />');
显示图像。
在成功回调中使用
$('#' + item_id).nextAll('.ajax_load:first').html('Voted!');
以特定的投票元素为目标。
关于javascript - Jquery 为单个元素添加 html(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4280815/