当我单击框中的任意位置时,如何正确选中此复选框?
<li class="vehicle-item">
<label>
<input type="checkbox" name="take-vehicle" />
<table summary="layout table">
<thead>
<tr>
<th colspan="3">2004 Austin Cooper</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="/media/icons/tick.png" alt="" /> Drivable</td>
<td><img src="/media/icons/cross.png" alt="" /> Convertible</td>
<td><img src="/media/icons/cross.png" alt="" /> Modified</td>
</tr>
</tbody>
</table>
</label>
</li>
正如您所看到的,我尝试将整个内容包装在 中,但这没有用。
所以我尝试编写一些 jQuery,
$('.vehicle-item').click(function() {
var $checkbox = $(this).find('input');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
这确实可以工作,但现在当我单击复选框本身时,它不会被选中。我假设是因为它正在被检查,然后 JS 立即取消检查它。但我不太确定我会怎么说“如果我单击除直接在复选框上之外的任何地方”?
<li class="vehicle-item">
<label>
<input type="checkbox" name="take-vehicle" />
<table summary="layout table">
<thead>
<tr>
<th colspan="3">2004 Austin Cooper</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="/media/icons/tick.png" alt="" /> Drivable</td>
<td><img src="/media/icons/cross.png" alt="" /> Convertible</td>
<td><img src="/media/icons/cross.png" alt="" /> Modified</td>
</tr>
</tbody>
</table>
</label>
</li>
As you can see, I've tried wrapping the whole thing in a <label>
but that didn't work.
So I tried writing some jQuery instead,
$('.vehicle-item').click(function() {
var $checkbox = $(this).find('input');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
Which does work, except now when I click the checkbox itself, it doesn't get checked. I'm assuming because it's being checked, and then the JS unchecks it immediately. But I'm not quite sure how I would say "if I click anywhere except directly on the checkbox"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查事件是否来自复选框本身,如下所示:
您无法在此处测试。
Check that the event didn't come from the checkbox itself, like this:
You cant test it here.
最近以另一种方式提出了这个问题,与某些孩子的事件冒泡和停止有关。
您需要确保在您的情况下不会为复选框本身触发该事件。
This question was asked in another way very recently, to do with event bubbling and stopping for certain children.
You need to ensure that the event does not fire for the checkbox itself in your case.