jQuery操作Table技巧大汇总

2020-05-24 21:42:31易采站长站整理

本文汇总了jQuery操作Table的技巧。分享给大家供大家参考,具体如下:

1.鼠标移动行变色

方法一:jQuery中的hover(fun(),fun())方法,参数一:第一个方法是添加样式功能,参数二:第二个方法是取消样式功能


$("#table1 tr").hover(function(){
$(this).children("td").addClass("hover")
},function(){
$(this).children("td").removeClass("hover")
})

方法二:


$("#table1 tr:gt(0)").hover(function() {
$(this).children("td").addClass("hover");
}, function() {
$(this).children("td").removeClass("hover");
});

2.奇偶行不同颜色


$("#table1 tbody tr:odd").css("background-color", "#bbf");
$("#table1 tbody tr:even").css("background-color","#ffc");
$("#table1 tbody tr:odd").addClass("odd")
$("#table1 tbody tr:even").addClass("even")

3.隐藏一行
$(“#table1 tbody tr:eq(3)”).hide();

4.隐藏一列

方法一:
$(“#table1 tr td::nth-child(3)”).hide();
方法二:
$(“#table1 tr”).each(function(){$(“td:eq(3)”,this).hide()});

5.删除一行


//删除除第一行外的所有行
$("#table1 tr:not(:first)").remove();
//删除指定行
$("#table1 tr:eq(3)").remove();

6.删除一列


//删除除第一列外的所有列
$("#table1 tr th:not(:nth-child(1))").remove();
$("#table1 tr td:not(:nth-child(1))").remove();
//删除第一列
$("#table1 tr td::nth-child(1)").remove();

7.得到(设置)某个单元格的值


//设置table1,第2个tr的第一个td的值。
$("#table1 tr:eq(1) td:nth-child(1)").html("value");
//获取table1,第2个tr的第一个td的值。
$("#table1 tr:eq(1) td:nth-child(1)").html();

8.插入一行:


//在第二个tr后插入一行
$("<tr><td>插入3</td><td>插入</td><td>插入</td><td>插入</td></tr>").insertAfter($("#table7 tr:eq(1)"));

9、获取每一行指定的单元格的值


var arr = [];
$("#table1 tr td:nth-child(1)").each(function (key, value) {
arr.push($(this).html());
});
var result = arr.join(',');

10、全选或全不选