表格的可讀性,很大一部分靠背景色差撐起來。這裡示範兩個小技巧:隔行換色,以及滑鼠移入時整列高亮。
用 jQuery 的序數選擇器,兩行就能搞定:
$("tr:odd").css("background-color","#eeeeee");
$("tr:even").css("background-color","#ffffff");
或者一行完成:
$("table tr:nth-child(odd)").css("background-color","#eeeeee");
:nth-child 用來匹配父元素下的第 N 個子元素,也接受 odd/even 關鍵字。兩者的差別在於::odd 是依「符合 tr 的集合」中的索引,而 :nth-child(odd) 是依「在父元素中所有子節點中的位置」。若表格裡混雜了其他標籤,兩者結果可能不同,實務上 :nth-child 的語意通常更符合期待。
用事件綁定,進去時上色、出來時還原:
$("tr").live({
mouseover: function(){
$(this).css("background-color","#eeeeee");
},
mouseout: function(){
$(this).css("background-color","#ffffff");
}
})
也可以拆成兩段 bind():
$("tr").bind("mouseover", function(){
$(this).css("background-color","#eeeeee");
})
$("tr").bind("mouseout", function(){
$(this).css("background-color","#ffffff");
})
不論 live() 或 bind(),都能一次綁定多個事件或分開處理。
live() 在 jQuery 1.7 之後已被標記為 deprecated,1.9 起正式移除。新專案請改用 on(),寫法如下:
$(document).on("mouseover mouseout", "tr", function(){
$(this).toggleClass("hover");
});
用 on() 做事件委派,不僅相容新版本,對於動態加入的表格列也能自動生效,不必重新綁定。