2015-09-04 58 views
3

我在<td><tr>元素的表中都有一个onclick事件。我需要当用户点击特定列(<td>)时,<tr>事件不会被触发,只有<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')}; 

当用户点击 '列3',这两个事件被触发,但我只想tdclick()是触发。

+1

你实现第3列是TR的孩子,对事件对象? – Onilol

+1

你能确保分号';'不在HTML中吗?但在'onclick'属性中 – Hacketo

+2

检查单击'td'的'cellIndex',如果它是'2',则停止传播。 – Teemu

回答

5

你需要做的是点击一个孩子时,停止父事件的传播,这是一个在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> 
+1

为什么您指的是jQuery? – Hacketo

+0

@Hacketo因为jQuery有[自己的事件来处理传播](https://api.jquery.com/event.stoppropagation/)。与天真地做相比,这往往更容易处理。 –

1

所有JavaScript事件被调用时第一个参数一个“事件”对象。该对象有一个“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') 
 
};

3

你需要停止事件的传播。 访问,你需要使用它作为你的函数的参数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>