javascript - 使用 jquery 选择表行,但在单击按钮时也选择行,如何防止这种情况发生?

标签 javascript jquery

当您单击表格行时,它会添加一个类,该类会更改其外观以反射(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​.stop​Propagation()点击按钮:

$('#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/

相关文章:

javascript - Greasemonkey 为一个简单的脚本抛出 SecurityError

asp.net - 如何让 JQuery 智能感知在 aspx 文件中工作?

javascript - 如何销毁 heatmap.js 实例?

javascript - 使用 jQuery 突出显示带有复选框的表格行

javascript - 为什么 mailto 正文不能将对象文字识别为 url 的一部分?

javascript - jQuery 在 Firefox 和 IE 11 中运行不佳

javascript - 无法使用 Javascript 将给定日期与今天的日期进行比较

javascript - 在 Rails 5.1.4 中包含 JS 脚本

jquery - 更新单个元素的背景而不是全部

javascript - Jquery 打印对象