我想在单击“有用”span class="upvote"
时更新范围中的 class="count"
文本。我使用 ajax 更新数据库中的值,然后使用结果显示在计数范围中。
但是,使用下面的代码它会更新所有这些。
我有以下 html
<div class="question">
<span class="upvote" data-id="1" data-cat="question"> Helpful <span class="count">2</span></span>
</div>
<div class="answers">
<span class="upvote" data-id="3" data-cat="answer"> Helpful <span class="count">15</span></span>
<span class="upvote" data-id="4" data-cat="answer"> Helpful <span class="count">66</span></span>
<span class="upvote" data-id="6" data-cat="answer"> Helpful <span class="count">0</span></span>
</div>
这是我的 jquery
$('.upvote').click(function(event) {
$.ajax({
url: 'http://localhost/ask/upvote',
type: 'POST',
data: {
cat_id: $(this).data('id'),
category: $(this).data('cat'),
},
dataType: 'json',
success: function(json) {
$(".upvote span").text(json);
}
});
event.preventDefault();
});
最佳答案
您可以保存所点击的赞成
的引用
$('.upvote').click(function(event) {
let $clicked = $(this); //reference saved
$.ajax({
url: 'http://localhost/ask/upvote',
type: 'POST',
data: {
cat_id: $(this).data('id'),
category: $(this).data('cat'),
},
dataType: 'json',
success: function(json) {
$clicked.find( ".count" ).text(json); //observe changes in this line
}
});
event.preventDefault();
});
关于javascript - 如何更新重复列表中的特定范围文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589557/