使用replaceWith()

时间:2016-03-22 12:08:40

标签: javascript backbone.js

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

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的新手,所以我以前从未使用过这种方法。你能告诉我为什么按钮消失了吗?这有什么不对?

澄清:当我打电话时,"取消关注",它会取消取消关注以正确关注(现在是以下)。但是,当我点击现在,而不是写#34;取消关注"按钮消失。

2 个答案:

答案 0 :(得分:1)

您正在调用.show()方法,该方法未返回JQueryObject .replaceWith()函数所需的$.post('/unfollow/', postParams, function(resp) { var followButton = $(".follow-button"); $(".unfollow-button").replaceWith( followButton ); followButton.show(); })

{{1}}

答案 1 :(得分:0)

我只是简单地解决了它;

$.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()不会保留按钮。

非常感谢。

相关问题