表格要做的兩件事:滑鼠移入時整列highlight、勾選後該列變色。這兩件事本質上都是「切換 class」,而 jQuery 的 toggleClass() 正好為此而生。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>隔行換色</title>
<script src="js/jquery-1.4.2.min.js"></script>
<style type="text/css">
body, table, td { font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
.h { background: #f3f3f3; color: #000; } /* hover 狀態 */
.c { background: #ebebeb; color: #000; } /* 已勾選狀態 */
</style>
</head>
<body>
<div id="aaa">
<form>
<table id="table" width="50%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td width="30" align="center">
<input type="checkbox" name="checkbox" class="check1" value="checkbox" />
</td><td></td><td></td>
</tr>
<!-- 其餘 7 列結構相同 -->
</table>
</form>
</div>
<script>
$(function () {
$("#table tr").hover(function () {
$(this).addClass("h");
}, function () {
$(this).removeClass("h");
});
$("input").click(function () {
if ($(this).attr("checked")) {
$(this).closest("tr").addClass("c");
} else {
$(this).closest("tr").removeClass("c");
}
});
});
</script>
思路清楚:移入加 class、移出移除;勾選時依狀態決定加或移除。
toggleClass() 會檢查元素上指定的 class 是否存在——不存在就加上,已存在就移除,這就是所謂的切換效果。若傳入第二個參數(switch),則可以強制「只加」或「只移除」。
<script>
$(function () {
$("#table tr").hover(function () {
$(this).toggleClass("h");
});
$("input").click(function () {
var d = $(this);
d.closest('tr').toggleClass("c", d.attr("checked"));
});
});
</script>
程式碼少了 if/else,意圖也更直接:hover 就是切換,勾選狀態就是那個 switch 參數。
prop() 取代 attr() 判斷勾選:自 jQuery 1.6 起,checked 屬於「目前狀態」而非「初始屬性」,應使用 $(this).prop('checked')。用 attr() 在部分版本會永遠回傳 "checked" 或 undefined,導致判斷失效。change:核取方塊的狀態變化用 change 比 click 更貼切,也能涵蓋程式化改值的情況。$('#table').on('change', 'input', handler) 即可。tr:nth-child(even) { background: #f7f7f7; }。jQuery 方案適用的是「需要與互動狀態協調」的情況。$('#table').on('mouseenter', 'tr', function () {
$(this).toggleClass('h');
}).on('mouseleave', 'tr', function () {
$(this).removeClass('h');
}).on('change', 'input[type="checkbox"]', function () {
$(this).closest('tr').toggleClass('c', this.checked);
});
直接用 this.checked 讀原生屬性最簡潔,也不必經過 jQuery 包裝。