我正在使用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;
});
答案 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)