【问题标题】:How to toggle class for clicked button in for loop?如何在for循环中切换单击按钮的类?
【发布时间】: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");
                }

【问题讨论】:

    标签: jquery django ajax


    【解决方案1】:

    我认为您获取按钮的id 的方式错误。使用jqueryonclick方法,你可以使用attr方法得到点击按钮的id,像这样

    $('.bookmark').click(function() { 
        var id = $(this).attr('id');
    });
    

    $('.bookmark').click(function() { 
          console.log($(this).attr('data-id'));
        console.log("BEFORE: " + $(this).find('i').attr('class'));
        $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
        console.log("AFTER: " + $(this).find('i').attr('class'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="bookmark_add" class="bookmark" name="bookmark" data-id="1">
        <i class="far fa-bookmark fa-lg"> Test 1</i>
     </button>
     
     <button id="bookmark_add" class="bookmark" name="bookmark" data-id="2">
        <i class="fad fa-bookmark fa-lg"> Test 2</i>
     </button>

    即使不是得到id,您也可以在上述click 事件定义中切换i 元素的class,就像这样

    $('.bookmark').click(function() { 
        $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
    });
    

    如果可行,请告诉我。

    【讨论】:

    • this.attr 以字符串形式给出值,data 以整数形式给出值,并且没有 id 它点击所有书签按钮。
    • 所以@iamcoder,你使用了错误的属性值。应该是$(this).attr('data-id');
    • @iamcoder 还有,没有 id 是什么意思,它会点击所有书签按钮。每个按钮都应该有一个唯一的 ID。
    • @iamcoder,使用class 名称而不是id 在所有按钮元素上都有click 事件。它会起作用的。请在上面找到更新的答案。
    • 所以现在我可以一键切换所有书签,如何只选择我正在点击的书签。
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多