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

jon*_*333 6 jquery jquery-selectors

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

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

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

我需要做的是排除在触发tr.title-row单击操作时单击一个href的内容(例如,警报不应该触发并且应该遵循链接).

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

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

以下是适用于的相同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>
Run Code Online (Sandbox Code Playgroud)

cha*_*tfl 5

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

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

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