2015-09-04 63 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>