为什么下面的代码不起作用。我阻止对事件的默认操作。然后我还是想检查一下这个框。
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);
});
您可能认为单击该复选框仍会选中该框..但事实并非如此。检查 fiddle 看看我的意思。
我也尝试过使用 attr
函数,但没有成功。
最佳答案
您必须将设置“checked”属性的代码放在单独的事件循环中:
setTimeout(function() { $('.checkbox').prop('checked', true); }, 1);
浏览器或库必须在事件处理程序返回后取消设置该复选框,因为它会在调用处理程序之前设置该复选框以响应单击。
关于javascript - 使用preventDefault后,为什么我不能用jquery选中一个框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15557038/