2012-11-07 17 views
3

你可以在這裏看到我的問題http://jsfiddle.net/eWh5F/76/() 我想要的是點擊TD和複選框應該選中/取消選中適用於TD內的複選框,但是當我有TD和TD裏面的桌子裏面有什麼解決方案? 我曾嘗試這樣的東西之下,但絲毫沒有運氣jQuery檢查一個TD內的正確的複選框

$("td").click(function(e) { 
var checkbox = $(':checkbox', $(this).parent()).get(0); 
var checked = checkbox.checked; 
if (checked == false) checkbox.checked = true; 
else checkbox.checked = false;}); 

回答

1

您可以使用prop方法:

$("td").click(function(e) { 
    $('> input[type=checkbox]', this).prop('checked', function(i, checked){ 
     return !checked 
    }) 
}); 

http://jsfiddle.net/jdy3d/

注意:checkbox選擇已被棄用。

+0

謝謝!按照我想要的方式工作:) –

+0

在此示例中,單擊複選框本身不起作用。 –

+1

@JohnnyC。你是對的,我已經更新了演示:http://jsfiddle.net/jdy3d/16/ – undefined

0

您可以使用e.stopPropagation();

$("td").click(function(e) { 
    e.stopPropagation(); 
    var checkbox = $('input[type="checkbox"]', $(this).closest('td')).get(0); 
    var checked = checkbox.checked; 
    if (checked == false) checkbox.checked = true; 
    else checkbox.checked = false; 
});​ 

:checked棄用使用input[type="checkbox"]代替

還利用$(this).closest('td')代替$(this).parent()

JSFIDDLE DEMO