2012-04-10 80 views
3

我用下面的代碼處理點擊。如何處理點擊<tr>而不是子元素?

表與輸入

<table> 
    <tr> 
     <td> 
      <input type="checkbox" /> 
     </td> 
    </tr> 
</table>​ 

Click處理

$('table tr').click(function(){ 
    alert('clicked'); 
});​ 

http://jsfiddle.net/n96eW/

它的工作很好,但如果我在TD複選框,單擊時的操控它。

有沒有辦法處理點擊的TR,但不觸發子元素?

回答

13

http://jsfiddle.net/n96eW/1/

在複選框添加另一個事件處理程序stopPropagation:

$('table tr').click(function(){ 
    alert('clicked'); 
}); 

$('table tr input').click(function(e) { 
    e.stopPropagation(); 
}); 
​ 
+0

這是執行此操作的正確方法。 +1 – Dutchie432 2012-04-10 10:06:28

+0

非常感謝! – yarikus 2012-04-10 10:07:23

+2

@YaroslavGlukhov http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work如果你不知道:) – 2012-04-10 10:15:20

4

您可以檢查event.target來過濾事件:

$('table tr').click(function(e){ 
    if(e.target.tagName.toLowerCase() != "input") { 
     alert('clicked'); 
    } 
});​ 
1

你也可以使用

$("tr").on('click',function() { 

    if (!$(event.target).is('input')) 
    alert('clicked'); 

}); 
相關問題