$(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/
答案 0 :(得分:1)
$(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>
答案 1 :(得分:0)
我认为您不必担心更改检查状态。
$(document).ready(function() {
$('#table tr').click(function() {
if ($('input[type=checkbox]', this).is(':checked')) {
$(this).addClass('bg-success');
} else {
$(this).removeClass('bg-success');
}
});
});
<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>