使用jQuery动态切换和更改id

时间:2012-04-25 01:06:36

标签: javascript jquery user-interface jquery-selectors twitter-bootstrap

我正在使用Twitter Bootstrap和jQuery

我想知道如何在“订阅/取消订阅”

之间切换

每次点击一个ajax请求,以便用户可以订阅/取消订阅

用户订阅后,我会显示一条消息“已订阅!” 如果用户后悔并想要取消订阅怎么办?

我想在一个按钮中同时具有两种功能。 我正在动态更改id,但它确实有效!

button class="btn" id="subscribe" data-toggle="button" data-loading-text="Loading..."  data-complete-text="Subscribed!">Subscribe
$(document).ready(function () {
        $('#subscribe').button();
        $('#unsubscribe').button();
    });




    $('#unsubscribe').click(function () {   
        $('#unsubscribe').button('loading');

        $.ajax({
            url: "<%= "#{root_url}unsubscribe_from/#{@collection.id}"%>" ,
            type: "GET",
            data: "",
            success: function(data) {
                $('#unsubscribe').button('complete');
                jQuery("#unsubscribe").attr("id","subscribe");
                jQuery("#subscribe").attr("data-complete-text").text("Subscribed!");
                }});
                return false;

            });


$('#subscribe').click(function () {   
    $('#subscribe').button('loading');
    // $('#subscribe').button('reset');
    $.ajax({
        url: "<%= "#{root_url}subscribe_to/#{@collection.id}"%>" ,
        type: "GET",
        data: "",
        success: function(data) {
            $('#subscribe').button('complete');
            jQuery("#subscribe").attr("id","unsubscribe");
            jQuery("#unsubscribe").attr("data-complete-text").text("Unsubscribe!");
            }});
            return false;

        });

2 个答案:

答案 0 :(得分:2)

$(document).on('click', '#subscribe, #unsubscribe', function(){
    var url; 
    var button_id; 
    var button_text; 
    var self = $(this);  
    self.button('loading');

   if( this.id === 'subscribe' )
    {
        url = "<%= "#{root_url}subscribe_to/#{@collection.id}"%>"; 
        button_id = 'unsubscribe';
        button_text = 'Subscribed!';  
    }
    else 
    {
        url = "<%= "#{root_url}unsubscribe_from/#{@collection.id}"%>"; 
        button_id = 'subscribe'; 
        button_text = 'Unsubscribed!'; 
    }

      $.ajax({
        url: url,
        type: "GET",
        data: "",
        success: function(data) {
               self.button('complete');
               self.attr("id", button_id);
               self.attr("data-complete-text", button_text).text(button_text);
            }});
            return false;

      });
})

答案 1 :(得分:1)

目前正在发生的事情是您的点击处理程序仅在开始时附加。因此,稍后更改id将不会附加处理程序。为此,您使用动态处理程序。

所以你应该关注

$(document).on("click", "#subscribe", function(){ 
  // ...
});  

$(document).on("click", "#unsubscribe", function(){ 
  // ...
});  

有关详细信息,请参阅JQuery On。之前你会使用live