如何在父元素的点击事件中排除子元素?

6

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

想象一下,一个表格单元格内有一个链接,并且通常情况下,点击任何表格行的空白区域(例如不是链接的区域)都会触发一些操作,例如手风琴/行的展开和折叠。

现在所发生的是,以下点击事件被触发,然后链接被跟踪(执行预期的操作)。

我需要的是排除从 tr.title-row 中点击 a href 的链接触发 tr.title-row 的点击动作(例如,警报不应该触发,链接应该被跟踪)。

这段 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个回答

5

可以检查行点击的目标,仅在目标不是<a>标签时运行代码:

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

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

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
});

顺便提一句,为了更好的代码,只需使用on而不是具名事件处理程序。

$(".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
});

1
就这个问题而言,.on('click').click()没有区别。请参见此处 - Blake Plumb
这是一种糟糕的代码风格,因为阅读 stopPropagation 部分的人会想知道它为什么存在。 - user2846569

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接