【发布时间】:2021-11-24 18:37:02
【问题描述】:
正在尝试将帖子添加到书签。 帖子在带有 for 循环的主页上。在单击单个帖子的添加书签按钮时,我无法获得切换类。
Django 视图
@login_required
def add_post_bookmark(request):
''' add post to bookmark '''
if request.POST.get('action') == 'post':
result = ''
is_bookmark = False
id_ = request.POST.get('id')
post = Post.objects.get(id=id_)
if post.bookmarks.filter(id=request.user.id).exists():
post.bookmarks.remove(request.user)
is_bookmark = False
post.save()
result = post.get_bookmarks_count()
else:
post.bookmarks.add(request.user)
is_bookmark = True
post.save()
result = post.get_bookmarks_count()
return JsonResponse({'result': result, 'bookmark_count': post.bookmarks.all().count(), 'post_id': id_, 'is_bookmark': is_bookmark})
Ajax
// bookmarks posts
$(document).on('click', '#bookmark_add', function (e) {
e.preventDefault();
var bookmarkCount;
var id = $(this).data("id");
$.ajax ({
type: 'POST',
url: '{% url "users:add-post-bookmark" %}',
data: {
'id': id,
csrfmiddlewaretoken: '{{ csrf_token }}',
action: 'post'
},
success: function (response) {
$('#'+id).empty().append(response['bookmark_count']);
console.log(response);
this_id = $(this).data("data-id"); //("id")
console.log(this_id); // undefined
$(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
},
error: function (xhr, errmsg, err) {
console.log("Error bookmarking post!");
}
});
})
index.Html
<span id="{{post.id}}" class="bookmark_coun text-muted">{{ post.get_bookmarks_count }}</span>
{% if request.user.is_authenticated %}
{% if request.user not in post.bookmarks.all %}
<button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="far fa-bookmark fa-lg"></i></button>
{% else %}
<button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="fad fa-bookmark fa-lg"></i></button>
{% endif %}
{% else %}
<a href="{% url 'users:register' %}" id="bookmark_add" class="bookmark"><i class="far fa-bookmark fa-lg"></i></a>
{% endif %}
问题: 每次我尝试添加书签时,它都会切换其他元素。我尝试通过 id 获取元素,但它也不是那样工作的。
试过了,还是不行:
this_id = $('#bookmark_add').data("id"); //("id")
console.log(this_id);
if (this_id === id) {
$("button[this_id]").find('i').toggleClass("fad fa-bookmark far fa-bookmark");
}
【问题讨论】: