这可能很简单,但我仍然没有找到解决方案,我想避免在完成 ajax 调用之前多次单击按钮。
这是我尝试过的:
<button id="btn_pay"></button>
$("#btn_pay").click( function() {
$('#btn_pay').prop('disabled', true);
Stripe.card.createToken(form, stripeResponseHandler);
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
alert("success");
},complete:function(){
//we re-enable the button
$('#btn_pay').prop('disabled', false);
}
});
问题: 如果我多次单击该按钮,会出现许多警报,就像该按钮仍处于事件状态一样,并且会完成许多 ajax 调用,而不是一次调用 jsut 1..
有什么想法吗?
最佳答案
你可以用一个简单的变量来控制它:
<button id="btn_pay"></button>
var disabled = false; // global var to control button state
$("#btn_pay").click( function() {
if (disabled) {
return;
}
Stripe.card.createToken(form, stripeResponseHandler);
disabled = true; // button is now blocked
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
disabled = false; // release button lock
alert("success");
},complete:function(){
disabled = false; // release button lock
},fail: function(){
disabled = false; // when fail, you need to release the lock too
}
});
}
具有事件处理程序的其他解决方案也可能适用于您,但这是实现此功能的更简单方法。
关于javascript - 避免多次点击一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864401/