javascript - 使用 Ajax 更改单击按钮的状态
问题描述
我正在一个 Django 项目中构建一个页面,该页面有多个评论,每个评论都可以通过文本旁边的按钮进行喜欢/不喜欢。所以页面有多个喜欢/不喜欢的按钮。
加载页面时按钮显示正常,我可以使用 Ajax 将数据发送到 Django 并更新我的数据库,这工作正常,我可以将数据返回给 Ajax 成功函数。
我无法解决的是 - 我如何更新被点击的实际按钮的状态。我可以根据下面的代码一起更新页面上所有按钮的状态(我知道毫无意义!),但看不到我如何引用单击的按钮。我已经尝试传递然后返回可以在警报中显示的按钮 ID,但不确定这是我应该使用的还是我从这里开始的地方?
HTML 模板
{% for comments in comments_page %}
<p>
<b>{{ comments.created_at }} ({{ comments.user_type }})</b>
{% if comments.comment_liked is False %}
<button class="comment btn btn-primary btn-xs"
id={{ forloop.counter0 }}
data-surveyid="{{ comments.id }}"
data-commentliked="True"
type="button">
<span class="glyphicon glyphicon-star-empty"></span>
</button>
{% else %}
<button class="comment btn btn-success btn-xs"
id={{ forloop.counter0 }}
data-surveyid="{{ comments.id }}"
data-commentliked="False"
type="button">
<span class="glyphicon glyphicon-star"></span>
</button>
{% endif %}
</p>
<p>{{ comments.comments }}</p>
<br>
{% endfor %}
Javascript/Ajax
{% block javascript %}
<script type="text/javascript">
$(function() {
$('.comment').click(function() {
var surveyid, commentliked, buttonid;
surveyid = $(this).attr('data-surveyid');
commentliked = $(this).attr('data-commentliked');
buttonid = $(this).attr('id');
$.ajax({
url: '/evaluations/validate_username/',
data: {
'surveyid': surveyid,
'commentliked': commentliked,
'buttonid': buttonid
},
dataType: 'json',
type: 'get',
success: function (data) {
alert(data.buttonid);
$(".comment").removeClass('comment btn btn-primary btn-xs').addClass('comment btn btn-success btn-xs');
}
});
});
});
</script>
{% endblock %}
解决方案
只需定位函数中单击的按钮success
:
{% block javascript %}
<script type="text/javascript">
$(function() {
$('.comment').click(function() {
// the button instance that was clicked
var clickedBtn = $(this);
var surveyid, commentliked, buttonid;
// also, you can use data-* to get the data attributes
// surveyid = clickedBtn.attr('data-surveyid');
// commentliked = clickedBtn.attr('data-commentliked');
surveyid = clickedBtn.data('surveyid');
commentliked = clickedBtn.data('commentliked');
buttonid = clickedBtn.attr('id');
$.ajax({
url: '/evaluations/validate_username/',
data: {
'surveyid': surveyid,
'commentliked': commentliked,
'buttonid': buttonid
},
dataType: 'json',
type: 'get',
success: function (data) {
alert(data.buttonid);
clickedBtn.removeClass('comment btn btn-primary btn-xs')
.addClass('comment btn btn-success btn-xs');
}
});
});
});
</script>
{% endblock %}
推荐阅读
- php - Laravel 检索一个 cookie 值
- python - 我的 Beautiful Soup 代码返回 TypeError: 'NoneType' object is not iterable
- wordpress - 我们可以在 wp bakery 的视觉作曲家的 wordpress 的单页上同时使用手风琴和制表符吗?
- python - 从字符串中提取数字的大多数 Pythonic 方法
- javascript - SVG 多边形无法突出显示
- ruby-on-rails - Logstash 上的 MongoDB 错误启动 admin.listCollections | 失败 | 参数数量错误(给定 2,预期 1)
- url - 如何仅在 https 上加载页面,即使是 http 请求
- javascript - AngularJS:当控件为空时,输入“必需”属性会完全删除其 ng-model
- python - 从数字列表中生成所有可能组合的百分比
- javascript - 使用“npm install wdio”安装 webdriverIO 时出错