更改按钮功能jQuery

Change button functionality jQuery

本文关键字:jQuery 功能 按钮      更新时间:2023-09-26

我在树枝中有这个代码

 {% if followsId == null %}
            <div id="followUser" class="follow" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow">
                Follow
            </div>
 {% else %}
            <div id="unFollowUser" class="follow" data-followsId="{{ followsId }}">
                Unfollow
            </div>
 {% endif %}

我只是想把内容和功能改为点击按钮,并用jQuery尝试了这个代码

$('#followUser').click(function () {
    var userId       = $(this).attr('data-userId'),
        action       = $(this).attr('data-action'),
        currentUser  = $(this).attr('data-currentUserId');
    $.ajax({
        method: 'POST',
        url: "/sci-profile/profile/follow",
        data: {
            userId: currentUser,
            profileUserId: userId,
            action: action
        },
        success: function(response)
        {
            $('#followUser').attr('id', 'unFollowUser')
                            .text('Unfollow')
                            .fadeOut(50)
                            .delay(50)
                            .fadeIn(50);
        }
    });
});

有了页面源代码,我在按钮上看到了不同的ID和不同的文本,但当第二次点击时,我调用了第一个按钮,就像它从未改变过一样。有没有办法刷新那个元素的内存,或者我从一开始就做错了什么?

我认为您的代码应该喜欢这个

{% if followsId == null %}
            <div data-action="follow" class="follow" data-user-id="{{ profileUserData.id }}">
                Follow
            </div>
 {% else %}
            <div data-action="unfollow" class="follow" data-user-id="{{ followsId }}">
                Unfollow
            </div>
 {% endif %}

无需存储当前登录的用户id,因为您可以从会话中获取:)

您的Ajax代码应该是这样的

$('.follow').click(function () {
    var _this= $(this);
    var userId = $(this).data('user-id');
    var action =$(this).data('action');
    $.ajax({
        method: 'POST',
        url: "/sci-profile/profile/follow",
        data: {
            profileUserId: userId,
            action: action
        },
        success: function(response)
        {
            if(action=="follow")
            {
                 _this.attr('data-action', 'unfollow').text('Unfollow');
            }
            else
            {
                 _this.attr('data-action', 'follow').text('Follow');
            }
        }
    });
});

希望你喜欢我的答案并投赞成票,如果正确,请标记为正确:)