更改按钮功能jQuery

Ste*_*sic 6 javascript ajax jquery

我在树枝上有这个代码

 {% 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 %}
Run Code Online (Sandbox Code Playgroud)

我只想将内容和功能更改为按钮点击并使用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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

Har*_*dja 3

我认为你的代码应该像这样

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

无需存储当前登录的用户 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');
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

希望您喜欢我的回答并投票,如果正确则标记为正确:)

  • +1,您可能想使用 `$(document).on("click",".follow",function(event){ var $this = event.target; ..` 动态附加(可能是ajax)按钮。 (2认同)