我可以在TR点击事件中排除按钮点击吗?

时间:2012-11-27 16:48:16

标签: javascript jquery twitter-bootstrap

我正在选中时突出显示一个表行但在其中一个单元格中我有一个按钮。当我单击按钮时,我触发了表行单击事件。是否有可能分开这两个?

我的两个电话目前看起来像这样:

$('table.table-striped tbody tr').on('click', function () {
   $(this).find('td').toggleClass('row_highlight_css');
}); 


$(".email-user").click(function(e) {
    e.preventDefault();
    alert("Button Clicked");
});

我的HTML看起来像这样:

<table class="table table-bordered table-condensed table-striped">
  <thead>
    <tr>
      <th>col-1</th>
      <th>col-2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Some Data</td>
      <td><button class="btn btn-mini btn-success email-user" id="email_123" type="button">Email User</button></td>
    </tr>
  </tbody>
</table>

知道如何阻止按钮点击事件触发行点击事件吗?

3 个答案:

答案 0 :(得分:16)

您必须使用stopPropagation

$(".email-user").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert("Button Clicked");
});

(另见:What's the difference between event.stopPropagation and event.preventDefault?

答案 1 :(得分:0)

我认为这是由事件冒泡引起的,请在e.stopPropagation();

之后尝试使用e.preventDefault();

答案 2 :(得分:0)

试试这个:

$('.table-striped').find('tr').on('click', function() {
    $(this).find('td').toggleClass('row_highlight_css');
});

$(".email-user").on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
});​