我在一个Bootstrap网站上工作,所以我必须把我所有的jQuery放在页面的底部,而不是头部。我在一些阅读中发现,这会导致jQuery事件触发两次的行为。实际发生的情况是点击量在不断累积。所以第一次点击,事件触发一次,然后第二次点击,它触发两次,以此类推。是什么导致了这种行为?
这个脚本的工作方式是通过运行PHP脚本来切换用户通知。这一切都很好。因此,当用户单击“订阅”链接时,它将订阅它们,并且链接将被重写为“取消订阅”链接。这可能就是我的问题所在。我只是不确定如何解决这个问题。无论如何,如果用户再次单击该链接,它会切换回“订阅”状态,依此类推。这是我的代码。
我在其他地方发现了一个技巧,我可以使用e.stopImmediatePropagation来消除这种行为,但它不起作用。
$('.subscription').bind('click', function(e) {
e.preventDefault()
e.stopImmediatePropagation()
var subscribe = jQuery(this).data('subscribe')
var forumId = jQuery(this).data('id')
var href = jQuery(this).data('href')
var selector = jQuery(this)
if (subscribe == 1) {
$('#email-notifications').modal('show')
$('.notify').on('click', function() {
var response = $(this).data('response')
if (response == 1) {
// subscribe the user
$.post('/discussion-boards/subscribe', { notify : response, forum : forumId }, function(data) {
// do nothing in the callback
});
// rewrite HTML and set subscription flag to 0
selector.html('<span class="glyphicon glyphicon-thumbs-down"></span> Unsubscribe from this Topic').data('subscribe', 0)
}
});
} else {
$.post('/discussion-boards/unsubscribe', { forum : forumId }, function(data) {
// do nothing in the callback
})
// rewrite HTML and set subscription flag to 1;
selector.html('<span class="glyphicon glyphicon-thumbs-up"></span> Subscribe to this Topic').data('subscribe', 1)
}
})发布于 2014-04-03 01:47:23
按照要求,以下是最终的解决方案:
$('.subscription').on('click', function(e) {
e.preventDefault()
e.stopImmediatePropagation()
var subscribe = jQuery(this).data('subscribe')
var forumId = jQuery(this).data('id')
var href = jQuery(this).data('href')
var selector = jQuery(this)
if (subscribe == 1) {
$('#email-notifications').modal('show')
$('.notify').unbind('click').bind('click', function() {
var response = $(this).data('response')
if (response == 1) {
// subscribe the user
$.post('/discussion-boards/subscribe', { notify : response, forum : forumId }, function(data) {
// do nothing in the callback
});
// rewrite HTML and set subscription flag to 0
selector.html('<span class="glyphicon glyphicon-thumbs-down"></span> Unsubscribe from this Topic').data('subscribe', 0)
}
});
} else {
$.post('/discussion-boards/unsubscribe', { forum : forumId }, function(data) {
// do nothing in the callback
})
// rewrite HTML and set subscription flag to 1;
selector.html('<span class="glyphicon glyphicon-thumbs-up"></span> Subscribe to this Topic').data('subscribe', 1)
}
})https://stackoverflow.com/questions/22794298
复制相似问题