1、表格變色
$('tbody>tr:odd').addClass('odd');
$('tbody>tr:even').addClass('even');
2、單項選擇列表radio
$('tbody>tr').click(function() {
$(this).addClass('selected').siblings().removeClass('selected')
.end()
.find(':radio').attr('checked',true);
});
對錶單中的行進行操作:增加類,去除原來的類,並對所選擇的項的屬性設置爲選中。
整體代碼:
<!DOCTYPE html>
<html>
<head>
<title>char 5.2.1</title>
<meta charset="utf-8" />
<style type="text/css">
.even{
background-color: #fff38f;
}
.odd{
background-color: #ffffee;
}
.selected{
background-color: #feeeee;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$('tbody>tr:odd').addClass('odd');
$('tbody>tr:even').addClass('even');
//$('tr:contains("王五")').addClass('selected');
$('tbody>tr').click(function() {
$(this).addClass('selected').siblings().removeClass('selected')
.end()
.find(':radio').attr('checked',true);
});
//獲取父結點相應的元素。也可以直接獲得$('tbody>tr :has(:checked).addClass('selected')')
$('table :radio:checked').parents("tr").addClass('selected');//一定要注意parents是複數!!
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th colspan="2">姓名</th>
<th>性別</th>
<th>暫住地</th>
</tr>
</thead>
<tbody>
<tr><td><input type="radio" name="choice" value=""/></td>
<td>王五</td>
<td>男</td>
<td>山東</td>
</tr>
<tr><td><input type="radio" name="choice" value="" checked="checked" /></td>
<td>趙六</td>
<td>男</td>
<td>山東</td>
</tr>
<tr><td><input type="radio" name="choice" value=""/></td>
<td>張三</td>
<td>男</td>
<td>山東</td>
</tr>
</tbody>
</table>
</body>
</html>
3、多項選擇Checkbox
多項選擇可以選擇多個高亮,主要在於高亮的判斷
<!DOCTYPE html>
<html>
<head>
<title>char 5.2.1</title>
<meta charset="utf-8" />
<style type="text/css">
.even{
background-color: #fff38f;
}
.odd{
background-color: #ffffee;
}
.selected{
background-color: #feeeee;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$('tbody>tr:odd').addClass('odd');
$('tbody>tr:even').addClass('even');
//對錶單進行操作
$('tbody>tr').click(function() {
//判斷是否是高亮了,使用hasclass()
if($(this).hasClass('selected')){
$(this).removeClass('selected')
.find(':checkbox').attr('checked',false);
}else{
$(this).addClass('selected')
.find(':checkbox').attr('checked', true);
}
});
//獲取父結點相應的元素。也可以直接獲得$('tbody>tr :has(:checked).addClass('selected')')
$('table :checkbox:checked').parents("tr").addClass('selected');//一定要注意parents是複數!!
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th colspan="2">姓名</th>
<th>性別</th>
<th>暫住地</th>
</tr>
</thead>
<tbody>
<tr><td><input type="checkbox" name="choice" value=""/></td>
<td>王五</td>
<td>男</td>
<td>山東</td>
</tr>
<tr><td><input type="checkbox" name="choice" value="" checked="checked" /></td>
<td>趙六</td>
<td>男</td>
<td>山東</td>
</tr>
<tr><td><input type="checkbox" name="choice" value=""/></td>
<td>張三</td>
<td>男</td>
<td>山東</td>
</tr>
</tbody>
</table>
</body>
</html>