使用replaceWith()将按钮替换为另一个按钮

Replacing a button with another using replaceWith()

本文关键字:按钮 替换 另一个 replaceWith 使用      更新时间:2023-09-26

现在我有两个按钮,可以通过查看关注者列表来关注或取消关注用户。例如,当某人已经在我的关注者中时,会出现取消关注按钮,在其他情况下,会出现关注按钮。

followProfile: function (e) {
    var personalData = $('#personal-information').serializeObject();
    var postParams = {
        csrfmiddlewaretoken: $.cookie('csrftoken'),
        personal_data: JSON.stringify(personalData)
    };
    $.post('/follow/', postParams, function(resp) {
        $(".follow-button").replaceWith( $(".unfollow-button").show() );
    })
},
unfollowProfile: function (e) {
    var personalData = $('#personal-information').serializeObject();
    var postParams = {
        csrfmiddlewaretoken: $.cookie('csrftoken'),
        personal_data: JSON.stringify(personalData)
    };
    $.post('/unfollow/', postParams, function(resp) {
        $(".unfollow-button").replaceWith( $(".follow-button").show() );
    })
},

这是我的问题;当我点击关注某人时,按钮会发生变化,变成取消关注。然而,当我再次单击取消关注时,按钮现在消失了。我是Javascript和Backbone.js的新手,所以我以前从未使用过这种方法。你能告诉我为什么按钮消失了吗?这里怎么了?

澄清:当我调用"unfollow"时,它将取代unfollow以正确地跟随(现在是跟随)。但当我现在点击关注,而不是写"取消关注"按钮消失了。

您正在调用方法.show(),该方法不返回.replaceWith()函数所期望的JQueryObject

$.post('/unfollow/', postParams, function(resp) {
    var followButton = $(".follow-button");
    $(".unfollow-button").replaceWith( followButton );
    followButton.show();
})

我只使用;

$.post('/unfollow/', postParams, function(resp) {
    document.getElementById('twitter-follow-button').style.display = 'inline';
    document.getElementById('twitter-unfollow-button').style.display = 'none';
})
$.post('/follow/', postParams, function(resp) {
    document.getElementById('twitter-follow-button').style.display = 'none';
    document.getElementById('twitter-unfollow-button').style.display = 'inline';
})

我需要保留按钮,所以我认为这对我来说是更简单、更好的解决方案。据我所知,replaceWith()并没有保留按钮。

非常感谢。