Javascript 事件onclick on<;td>;及<;tr>;

Javascript 事件onclick on<;td>;及<;tr>;,javascript,Javascript,我在表中的和元素上都有一个onclick事件。我需要在用户单击特定列()时,不会触发事件,只触发事件 怎么做 例如: HTML: <tr onclick='trclick();'> <td>Column 1</td> <td>Column 2</td> <td onclick='tdclick();'>Column 3</td> </tr> 当用户单击“第3列”时,两个事件都会被触发,但我只想触发t

我在表中的
元素上都有一个onclick事件。我需要在用户单击特定列(
)时,不会触发
事件,只触发
事件

怎么做

例如:

HTML:

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

当用户单击“第3列”时,两个事件都会被触发,但我只想触发
tdclick()

您需要做的是在单击子事件时停止父事件的传播,这在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,您需要传递一个
事件
参数:

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

在第一个参数中使用“event”对象调用所有javascript事件。此对象有一个“stopPropagation”方法,该方法防止触发更高层次DOM节点上相同事件的侦听器

在MDN上有一个与您一样的示例:

在您的示例中,您可以在“tdclick”上停止传播:

功能tdclick(e){
e、 停止传播();
console.log('td clicked')

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

函数trclick(){console.log('trclicked');
函数tdclick(事件){
log('td clicked');
event.stopPropagation()
};

第1栏
第2栏
第3栏
我喜欢这种方法:

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

您可以在函数输入中使用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>

功能颜色变换器(el){
el.style.backgroundColor='#007d00';
}
点击我

您意识到第3列是tr的子列,对吗?您能确保分号
不在HTML中?但是在
onclick
attribute中,检查单击的
td
cellIndex
,如果它是
2
,则停止传播。@Teemu只需在
tdclick
中停止传播,刚刚修复了它@hacketto你指的是jQuery吗?@hacketto,因为jQuery有自己的功能。这比单纯地做更容易操作。
<script>
    tdclick(){
     //do something...
    }
</script>
<!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>