使用preventDefault后,为什么不能选中带有jquery的框? [英] after using preventDefault, why can't i check a box with jquery?
问题描述
为什么下面的代码不起作用.我阻止对该事件执行默认操作.然后我还是要选中该框.
How come the following code does not work. I prevent the default action on the event. Then I want to check the box anyway.
html
<input type="checkbox" class="checkbox" />
javsacript
$('.checkbox').click( function(e) {
e.preventDefault();
// some logic happens... now i may decide to check the box (in this case we want to check it for testing)
$('.checkbox').prop('checked',true);
});
您可能会认为单击该复选框仍会选中该复选框.检查小提琴,看看我的意思.
You would think clicking the checkbox would still check the box.. but it doesnt. Check the fiddle to see what I mean.
我也尝试过使用attr
函数,但没有任何运气.
I have also tried using the attr
function without any luck.
推荐答案
您必须将用于设置"checked"属性的代码放在单独的事件循环中:
You have to put the code that sets the "checked" property in a separate event loop:
setTimeout(function() { $('.checkbox').prop('checked', true); }, 1);
事件处理程序返回后,浏览器或库都必须取消设置该复选框,因为它会响应调用处理程序之前的 进行设置.
Either the browser or the library has to un-set the checkbox after the event handler returns, because it sets it in response to the click before the handler is invoked.
这篇关于使用preventDefault后,为什么不能选中带有jquery的框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!