简体   繁体   English

绑定解除绑定 onclick 事件不适用于 Ajax

[英]Bind Unbind onclick event not working with Ajax

I am having an issue with bind & unbind onClick listener using JQuery Ajax.我在使用 JQuery Ajax 绑定和取消绑定 onClick 侦听器时遇到问题。

How to unbind on click event that it can't be clicked multiple times, but bind it if ajax fails.如何在无法多次点击的点击事件上解除绑定,但如果ajax失败则绑定。 this is what I have tried so far.这是我到目前为止所尝试的。

$('#test').on('click', function (e) {  
 e.preventDefault();
 alert('clicked');
 $( "#test" ).off( "click");// works fine,remove on click listner
 // Ajax function
 // done()  // Do nothing.
 // error() // bind it again so it can be clicked.
});

https://jsfiddle.net/khirad1996/4nLdvq9s/2/ https://jsfiddle.net/khirad1996/4nLdvq9s/2/

You can disable the button while the call is happening, and re-enable if there is an error!您可以在通话过程中禁用按钮,如果出现错误则重新启用!

 const fakeAjax = time => new Promise(r => setTimeout(() => r(Math.random() >.5), time)) const button = document.querySelector('button'); button.addEventListener('click', async function() { this.disabled = true; error = await fakeAjax(1000); this.disabled = error; });
 <button>Ajax Call</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM