2012-07-08 50 views
0

我有以下HTML表格。每行包含一個複選框,後跟一些文本。使用jQuery複選框突出顯示錶格行

<table> 
    <tr> 
     <td><input type="checkbox" /></td> 
     <td>Name</td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" /></td> 
     <td>Name2</td> 
    </tr> 
</table> 

我需要一些幫助寫一個腳本,將突出(添加類)已檢查並取消選中將刪除類的行。

回答

2

http://codebins.com/codes/home/4ldqpb8

$(":checkbox").change(function() { 
     $(this).closest("tr").toggleClass("highlight", this.checked) 
    }) 
+0

出於興趣,爲什麼選擇最接近而不是父母? – 2013-05-18 08:21:35

+0

因爲CLosest找到第一個,然後停止搜索其他人,而父母一直走到文檔的頂部,並且如果嵌套了trs,它將在所有這些元素上處理toggleClass。所以最接近的是更快,更高效和更少的錯誤機會。 – gaurang171 2013-05-20 16:00:56

0
$('[type="checkbox"]').change(function(){ 
    $(this).parents('tr').toggleClass('highlight') 
}) 
+0

你好bruv,小記':)'使其'是( ':檢查')',因爲它勾選時應該突出顯示。 – 2012-07-08 01:54:38

+0

或者你可以在html中添加默認選中的複選框。除非他有動態元素,否則我會這樣做,並保持js更小。 – elclanrs 2012-07-08 01:56:47

+0

確實':)'!!同意 – 2012-07-08 02:01:09

0

演示http://jsfiddle.net/328QV/

代碼

$(document).ready(function() { 
    $("#Table input").click(function() { 
     if ($(this).is(":checked")) { 
      $(this).parent().parent().addClass("highlight"); 
     } else { 
      $(this).parent().parent().removeClass("highlight"); 
     } 
    }); 
});​ 
2
$("#yourTableId input:checkbox").change(function() { 
     var $this = $(this); 
     if ($this.is(":checked")) { 
      $this.closest("tr").addClass("highlight"); 
     } else { 
      $this.closest("tr").removeClass("highlight"); 
     } 
    }); 
0

看看這個fiddle

JS

$(document).ready(function() { 
    $("input:checkbox").change(function() { 
     alert(); 
     if ($(this).prop("checked") == true) { 
      $(this).closest('tr').addClass("checked"); 
     } else $(this).closest('tr').removeClass("checked"); 
    }); 
}); 

CSS

.checked { 
    background-color:red; 
} 
相關問題