如何从父级点击事件中排除子项?

时间:2013-01-06 00:19:49

标签: jquery jquery-selectors

我遇到一个表格行有点击事件的问题,但是当用户点击其中一个表格行的单元格中的链接时,我不希望触发该行的点击事件。

想象一下,表格单元格中有一个链接并且通常单击任何表格行(例如不是链接)的空​​白区域会导致某些操作,如手风琴/行折叠和展开。

正在发生的是下面的点击事件正在触发,然后跟踪链接(预期的操作)。

我需要做的是排除点击触发tr.title-row点击操作的a中的href(例如警报不应该触发并且应该遵循链接)。

这个jQuery代码正在为标题行设置点击事件(例如该行中的所有TH,任何单元格等)

$(document).ready(function() {
$(".report tr.title-row").click(function() {
    alert('I am firing!');
});

以下是适用于的相同HTML:

<table width="100%" cellspacing="0" cellpadding="0" border="0" class="report">
  <tbody>
    <tr class="title-row">
      <th width="340"><span class="title">Test</span>
      </th>
      <th width="130" class="center-cell">Test</th>
      <th width="90" class="status"></th>
      <th></th>
      <th width="160"> <a target="_self" href="http://www.google.com" class="link-class sub-class">I am triggering the TR click event</a>
      </th>
    </tr>
    <tr>
      <td class="sub-row" colspan="5">
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
          <tbody>
            <tr>
              <td><strong>SubRow</strong>
              </td>
              <td width="90" class="status"><span class="sub">Sub</span>
              </td>
              <td width="120"></td>
              <td width="160"><a title="Continue" href="http://www.yahoo.com">Something</a>
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:5)

如果目标不是target标记,则可以检查行点击的<a>并仅运行代码:

$(".report tr.title-row").click(function(event) {

    if( ! $(event.target).is('a') ){
        alert('I only fire when A not clicked!');
     }
});

答案 1 :(得分:2)

停止将事件冒泡到行

$(".report tr.title-row").click(function() {
    alert('I am firing!');
});

$(".report tr.title-row a").click(function(ev){
    // link clicked
    // so something

    ev.stopPropagation(); // stop triggering the event to the table row
});

btw ...为了更好的代码,只需使用on而不是命名的eventhandler

$(".report tr.title-row").on( 'click', function() {
    alert('I am firing!');
});

$(".report tr.title-row a").( 'click', function(ev){
    // link clicked
    // so something

    ev.stopPropagation(); // stop triggering the event to the table row
});