在 <td> 和 <tr> 上触发 onclick 事件

15

在表格中,我有一个同时存在于 <td><tr> 元素上的 onclick 事件。当用户点击特定列(<td>)时,我需要仅触发 <td> 上的事件,而不是 <tr> 上的事件。

如何实现?

示例:

HTML:

<tr onclick='trclick();'>
<td>Column 1</td>
<td>Column 2</td>
<td onclick='tdclick();'>Column 3</td>
</tr>

JS:

function trclick(){console.log('tr clicked')};
function tdclick(){console.log('td clicked')};

当用户点击“第三列”时,两个事件都会触发,但我希望只有tdclick()被触发。


1
你知道第三列是 tr 的子元素,对吧? - Onilol
1
你能确保分号 ; 不在 HTML 中,而在 onclick 属性中吗? - Hacketo
2
检查所点击的tdcellIndex,如果是2,则停止传播。 - Teemu
1
@Teemu 只需要在 tdclick 中停止事件传播。 - Hacketo
刚刚修好了 @Hacketo - delphirules
如何停止事件传播 @Hacketo - delphirules
5个回答

17

当子元素被点击时,您需要停止父元素事件的传播。在jQuery中非常容易实现,但是要做更多的工作:

function trclick(){
    console.log('tr clicked')
};

function tdclick(e){ 
    if (!e) var e = window.event;                // Get the window event
    e.cancelBubble = true;                       // IE Stop propagation
    if (e.stopPropagation) e.stopPropagation();  // Other Broswers
    console.log('td clicked');
};  

请注意,对于Firefox浏览器,您需要传递一个event参数:

<td onclick='tdclick(event)'>Column 3</td>

3
你为什么要提到jQuery? - Hacketo
1
@Hacketo 因为jQuery有他们自己的事件处理程序来处理传播。与原始方法相比,这种方法往往更容易使用。 - Spencer Wieczorek

6

您需要停止事件的传播。 要访问事件对象,您需要将其作为函数tdclick的参数使用。

function trclick(){console.log('tr clicked')};

function tdclick(event){
    console.log('td clicked'); 
    event.stopPropagation()
};
<table><tbody>
<tr onclick='trclick();'>
<td>Column 1</td>
<td>Column 2</td>
<td onclick='tdclick(event);'>Column 3</td>
</tr>
</tbody></table>


2

您可以在函数输入中使用el,并将变量传递给它,在您想要调用它的任何地方都可以这样做。

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function colorChanger(el){
    el.style.backgroundColor = '#007d00';
}

</script>
</head>
<body>
  <table>
    <tr onclick="colorChanger(this);">
      <td onclick="colorChanger(this);">click me</td>
    </tr>
  </table>
</body>
</html>

1
所有的JavaScript事件都会在第一个参数中传递一个“event”对象。这个对象有一个“stopPropagation”方法,可以阻止在更高层次的DOM节点上注册的相同事件监听器被触发。
MDN上有一个与您类似的示例:https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Examples#Example_5:_Event_Propagation 在您的示例中,您可以只在“tdclick”上停止传播:

function tdclick(e){
  e.stopPropagation();
  console.log('td clicked')
};


0

我喜欢这种方法:

<td style='cursor: pointer;' tdclick(event);'></td>

然后JS

<script>
    tdclick(){
     //do something...
    }
</script>

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