jQuery动态添加删除表格的行和列

本文介绍了一个使用jQuery操作HTML表格的示例,包括动态添加和删除行、列,并演示了如何改变单元格背景颜色。该示例通过简单的按钮交互实现表格元素的动态管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style type="text/css">
.cl1{
background-color:#FFFFFF;
}
.cl2{
background-color:#FFFF99;
}
</style>
<script type="text/javascript" src="css_js/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var rowCount = 0;
var colCount = 2;
 
function addRow(){
rowCount++;
var rowTemplate = '<tr class="tr_'+rowCount+'"><td>'+rowCount+'</td><td class="cl1">内容'+rowCount+'</td><td class="cl1"><a href="#" onclick=delRow('+rowCount+')>删除</a></td></tr>';
var tableHtml = $("#testTable tbody").html();
tableHtml += rowTemplate;
$("#testTable tbody").html(tableHtml);
}
 
function delRow(_id){
$("#testTable .tr_"+_id).hide();
rowCount--;
}
 
function addCol(){
colCount++;
$("#testTable tr").each(function(){
 
var trHtml = $(this).html();
trHtml += '<td onclick="delCol('+colCount+')">增加的td</td>';
$(this).html(trHtml);
});
 
}
 
function delCol(_id){
 
$("#testTable tr").each(function(){
$("td:eq("+_id+")",this).hide();
});
colCount--;
}
 
function mover(_id){
$("#testTable tr:not(:first)").each(function(){
$("td:eq("+_id+")",this).removeClass("cl1");
$("td:eq("+_id+")",this).addClass("cl2");
});
}
 
function mout(_id){
$("#testTable tr:not(:first)").each(function(){
$("td:eq("+_id+")",this).removeClass("cl2");
$("td:eq("+_id+")",this).addClass("cl1");
});
}
</script>
<title>jquery操作表格测试</title>
</head>
<body>
<table id="testTable" border="1" width="500">
<tr>
<td>序号</td>
<td onmouseover="mover(1);" onmouseout="mout(1);">内容</td>
<td onmouseover="mover(2);" onmouseout="mout(2);">操作</td>
</tr>
</table>
<input type="button" value="添加行" onclick="addRow();"/>
<input type="button" value="添加列" onclick="addCol();"/>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值