简体   繁体   English

在复选框单击事件中使用preventDefault

[英]Using preventDefault in checkbox click event

I have a checkbox and the requirement is that when the user clicks it, instead of immediately changing its state, a modal window should pop up asking them a yes/no question. 我有一个复选框,要求是用户单击它时,而不是立即更改其状态时,应弹出一个模式窗口,询问他们是/否的问题。 Depending on their answer, the checkbox should either become checked or remain unchecked. 根据他们的答案,该复选框应变为选中状态或保持未选中状态。

I thought that this requirement should be handled using Event.preventDefault() but when I tried to do it I discovered that when I exit the event handler, the checkbox is reverted to its original state, regardless of my programmatic attempts to set the state in the handler. 我认为应该使用Event.preventDefault()处理此要求,但是当我尝试执行此操作时,我发现退出事件处理程序时,无论我是否以编程方式尝试将状态设置为,复选框都将还原为原始状态。处理程序。

 $(function() { $(":checkbox").click(function(e) { e.preventDefault(); $(this).prop("checked", confirm("Confirm to check the checkbox")); }); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <label for="checkbox">Click me</label> <input type="checkbox" id="checkbox"> </form> 

So how can I implement the required behavior? 那么如何实现所需的行为?

The problem is because you called preventDefault() at all. 问题是因为您根本调用了preventDefault() You don't need it in this case as the checked state is entirely dependant on the outcome of the confirm() call. 在这种情况下,您不需要它,因为checked状态完全取决于confirm()调用的结果。

Also note that you should use the change event, not click , when dealing with checkboxes. 另请注意,处理复选框时,应使用change事件,而不要click Try this: 尝试这个:

 $(function() { $(":checkbox").change(function(e) { $(this).prop("checked", confirm("Confirm to check the checkbox")); }); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <label for="checkbox">Click me</label> <input type="checkbox" id="checkbox"> </form> 

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

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