当您单击表格行时,它会添加一个类,该类会更改其外观以反射(reflect)它已被选中。
$('#my_table tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
但是,我在列中也有一些按钮,可让您执行特定于该行的操作:
Item Amount Action
--------------------------------
Apple 10 [Buy] [Delete]
Banana 5 [Buy] [Delete]
Orange 14 [Buy] [Delete]
当我单击其中一个单独的按钮时,它还会触发要添加的表行“.selected”类,但我不希望在单击按钮时发生这种情况。
最佳答案
您可以使用 Event.stopPropagation()
点击按钮:
$('#my_table tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
$('#my_table tbody').on( 'click', 'button', function (e) {
e.stopPropagation();
});
.selected{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_table">
<thead>
<th>Item</th>
<th>Amount</th>
<th>Action</th>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>10</td>
<td><button>[Buy]</button><button>[Delete]</button></td>
</tr>
<tr>
<td>Banana</td>
<td>5</td>
<td><button>[Buy]</button><button>[Delete]</button></td>
</tr>
<tr>
<td>Orange</td>
<td>14</td>
<td><button>[Buy]</button><button>[Delete]</button></td>
</tr>
</tbody>
</table>
关于javascript - 使用 jquery 选择表行,但在单击按钮时也选择行,如何防止这种情况发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403820/