1
我有一個複選框(它使用Bootstrap Switch庫作爲開/關切換)以通過AJAX激活和停用用戶。防止Javascript確認()在複選框狀態更改
當用戶取消選中此功能被激發箱:
$('.user-status-ckbx').on('switchChange.bootstrapSwitch'...
的確認()則會彈出一個對話框,詢問用戶是否自己一定要DE /激活用戶。如果用戶單擊「否」的按鈕,使用送回其原始狀態:
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
我遇到的問題是,每個toggleState()運行時,switchChange.bootstrapSwitch也再次運行。這會產生一個無結束的confirm()消息,只有在用戶確認消息時纔會消失。
有沒有一種有效的方法來防止switchChange.bootstrapSwitch方法運行基於真正的用戶點擊與編程生成的切換?
我已經嘗試過:
e.originalEvent !== undefined
和
e.which
在其他類似的問題的建議,但沒有這些工作,也沒有他們甚至會出現在「e」的對象。 ..
<script>
$(".user-status-ckbx").bootstrapSwitch('size', 'mini');
$(".user-status-ckbx").bootstrapSwitch('onText', 'I');
$(".user-status-ckbx").bootstrapSwitch('offText', 'O');
//ajax to activate/deactivate user
$('.user-status-ckbx').on('switchChange.bootstrapSwitch', function(e){
var currentDiv = $("#" + e.currentTarget.id).bootstrapSwitch('state');
if(currentDiv == false){
var confirmed = confirm("Are you sure you wish to deactivate this user? They will no longer be able to access any forms.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
} else {
var confirmed = confirm("Are you sure you wish to activate this user? Deactivated users which were previously active will have the same permissions prior to their de-activation unless changed manually.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
}
});
function changeActivationStatus(userId){
$.post("{{ path('isactive') }}", {userId: userId})
.done(function(data){
console.log("Finished updating " + userId);
})
.fail(function(){
console.log("User could not be updated");
});
};
</script>
從Bootstrap Switch Doc:「方法toggleState可以接收可選的第二個參數skip,如果爲true,則不執行switchChange事件,默認值爲false。」 原來,您甚至不需要將onSwitchChange選項設置爲false。這樣做會產生相反的效果,即在用戶點擊「確認」時不切換狀態。我會相應地編輯你的答案。謝謝 – Ravioli87