jquery - 复选框在带有 jQuery 检查取消选中功能的表行中不起作用
问题描述
$(document).ready(function() {
$('#table tr').click(function() {
if ($('input[type=checkbox]', this).is(':checked')) {
$(this).removeClass('bg-success');
$('input[type=checkbox]', this).prop('checked', false);
} else {
$(this).addClass('bg-success');
$('input[type=checkbox]', this).prop('checked', true);
}
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" class="table">
<tr class="bg-success">
<th><input type="checkbox" name="param[1]" value="1" checked></th>
<td><strong>abc</strong></td>
<td>abc</td>
<td>abco</td>
</tr>
<tr>
<th><input type="checkbox" name="param[2]" value="1"></th>
<td><strong>def</strong></td>
<td>def</td>
<td>def</td>
</tr>
<tr>
<th><input type="checkbox" name="param[3]" value="1"></th>
<td><strong>ghi</strong></td>
<td>ghi</td>
<td>ghi</td>
</tr>
我在每一行都有带有复选框的表格。点击表格行后,复选框被选中或取消选中。那没问题。但是,如果我在复选框内完全单击,它就不起作用。谢谢你的帮助。
这是我在 FIDDLE 中的代码。https://jsfiddle.net/o9w6v4pu/
解决方案
$(document).ready(function() {
$('#table tr').on('click', function(e) {
var $tr = $(this);
var $checkbox = $('input:checkbox', this);
if (!$checkbox.is(e.target)) {
// the user did not click the checkbox, so flip its state
$checkbox.prop('checked', !$checkbox.prop('checked'));
}
//toggle the bg-success class
$tr.toggleClass('bg-success', $checkbox.prop('checked'));
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" class="table">
<tr class="bg-success">
<th><input type="checkbox" name="param[1]" value="1" checked></th>
<td><strong>abc</strong></td>
<td>abc</td>
<td>abco</td>
</tr>
<tr>
<th><input type="checkbox" name="param[2]" value="1"></th>
<td><strong>def</strong></td>
<td>def</td>
<td>def</td>
</tr>
<tr>
<th><input type="checkbox" name="param[3]" value="1"></th>
<td><strong>ghi</strong></td>
<td>ghi</td>
<td>ghi</td>
</tr>
</table>
推荐阅读
- ios - Crashlytics(没有 Fabric)没有显示崩溃 iOS
- ionic-framework - 如何在ionic 3中单击提交后重置输入文件
- php - Symfony 4 - 路由:“在此服务器上找不到请求的 URL”
- swift - 无法捕获 NSStoryboard.instantiateController(withIdentifier:
- javascript - 如何提交表格在哪?在 GET 方法上使用而不是 =
- ansible - 需要其他 ansible 角色的 Ansible 角色
- ios - 使用 For 循环更改 UIImageView 的图像
- c# - 有没有办法锁定一对独特的对象?
- javascript - JavaScript 确定点击事件的原因
- dataframe - 如果列尚不存在,则从列表中创建 pyspark df 中的列