2012-04-25 56 views
2

我做這個click事件:如果單擊複選框,防止TD onclick發射?

$('table tbody td').click(function (e) { 
    // How to check if checkbox was clicked before doing the alert below? 
    alert("td clicked"); 
} 

但是在我的表,我有一些TD與複選框,單擊時,導致事件觸發。有沒有一種方法可以在Jquery中指定,以檢查td中的點擊是否在複選框上並且不提醒?

+0

你可以列出的問題嗎? – iambriansreed 2012-04-25 03:10:46

回答

0

讀這個假設有問題的複選框是在同一個錶行作爲可點擊的細胞。

$('table tbody td').click(function (e) { 

    if(!$(this).parent().find(':checkbox').prop("checked")) 
     return; 

    alert("td clicked"); 
} 
1

你可以告訴jQuery來從你的checkbox傳播事件,您td

$('table tbody td input[type=checkbox]').click(function (e) { 
    // How to check if checkbox was clicked before doing the alert below? 
    e.stopPropagation(); 
} 

停止複選框基本上,這是因爲當你點擊checkbox,從您的複選框,瀏覽器將泡沫是click盛會,您的複選框的父級,然後上升到document,上面的代碼基本上停止了複選框的傳播。

有在event bubbling

0

您可以使用傳遞給點擊功能在eventObject找到目標,並用它來決定該怎麼做:

$("table tbody td").click(function(e){ 
    if(e.target.nodeName.toUpperCase() == "INPUT"){ 
     alert("It's an input!"); 
    }else{ 
     alert("It's not an input!");  
    } 
}); 
+0

我不知道爲什麼downvotes。這正是我如何解釋他的問題。聽起來好像是td中的複選框,他想阻止點擊它同時觸發td事件。雖然我會將其更改爲明確檢查複選框。 'e.target.type =='checkbox'' http://jsfiddle.net/xGpfU/2/ – mrtsherman 2012-04-25 03:21:58

+0

我把它作爲輸入,因爲無線電輸入可能也屬於這個類別。檢查如'e.target.type =='複選框'|| e.target.type =='radio''也可以工作,如果這是提問者的意圖 – 2012-04-25 03:28:33