我希望我页面上的用户能够根据需要多次订阅和取消订阅,而无需在每次点击之间刷新整个页面...
为此,我有一个订阅/取消订阅按钮...
它工作正常......当用户点击它时更新数据库并切换到oppsite(订阅 - >取消订阅,反之亦然)......
问题是按下按钮并随后按下按钮后,新按钮现在处于非活动状态,用户必须刷新整个页面才能再次激活...
我该如何解决这个问题?
需要它的人的代码:
c.php(频道页面)/ v.php(视频页面)//两个页面上的设置与此按钮完全相同
<div class="row" id="subscribeAll">
<div class="col-xl-9 col-lg-8 col-md-7 col-sm-6 col-xs-12 col-12">
// some stuff (not relevant)
</div>
<div class="col-xl-3 col-lg-4 col-md-5 col-sm-6 col-xs-12 col-12" id="subscribe">
// if user logged in show content below
// if user viewing own channel/video
<button type="button" class="btn btn-lg btn-dark" disabled>
Subscribers // show number of subscribers
</button>
// else
<button type="button" class="btn btn-lg // if not subscribed btn-success // else btn-danger" id="// if not subscribed subscribeButton // else unsubscribeButton" value="// randomstring of user whose channel/video user is watching">
// if not subscribed Subscribe // else Unsubscribe // show number of subscribers
</button>
// else if user not logged in show content below
<button type="button" class="btn btn-lg btn-dark" disabled>
Subscribers // show number of subscribers
</button>
</div>
</div>
的jquery.js
// Subscribe
$(document).ready(function(){
"use strict";
$('button[id^="subscribeButton"]').on('click',function(){
var self = $(this);
var randomStringUser = self.val();
$.ajax({
type: "POST",
url:'subscribe.php',
data:"randomStringUser="+randomStringUser,
success:function(){
var subscribe = self.closest('#subscribeAll').find('[id^="subscribe"]');
subscribe.load(location.href + " #subscribe>*", "");
}
});
});
});
// Unsubscribe
$(document).ready(function(){
"use strict";
$('button[id^="unsubscribeButton"]').on('click',function(){
var self = $(this);
var randomStringUser = self.val();
$.ajax({
type: "POST",
url:'unsubscribe.php',
data:"randomStringUser="+randomStringUser,
success:function(){
var subscribe = self.closest('#subscribeAll').find('[id^="subscribe"]');
subscribe.load(location.href + " #subscribe>*", "");
}
});
});
});
希望有人能帮忙......
答案 0 :(得分:1)
尝试从以下格式更改我们的选择器
$('button[id^="unsubscribeButton"]').on('click',function(){
到
$(document).on('click','button[id^="unsubscribeButton"]', function(){
这允许jQuery查找动态添加的元素,因为当页面首次呈现时它们不存在于DOM中,通过使用$(document).on('click')文档元素仍然存在,因此单击方法仍然触发