我在表中的<td>
和<tr>
元素上都有一个onclick事件。我需要当用户点击特定的列(<td>
)时,<tr>
事件不会被触发,只有<td>
事件会被触发。
该怎么做呢?
示例:
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')};
当用户点击'Column 3‘时,两个事件都会被触发,但我只希望触发tdclick()
。
发布于 2015-09-05 02:21:06
您需要做的是在单击子事件时停止父事件的传播,这在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');
};
注意,对于火狐,你需要传递一个event
参数:
<td onclick='tdclick(event)'>Column 3</td>
发布于 2015-09-05 02:21:53
您需要停止事件的传播。要访问事件对象,需要将其用作函数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>
发布于 2015-09-05 02:21:38
所有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')
};
https://stackoverflow.com/questions/32404185
复制相似问题