实现对表格的一些简单操作:添加一行、删除一行、上移选中行、下移选中行
一.html代码:
<a href="#" id="addLine">添加一行</a> <a href="#" id="removeLine">删除一行</a> <a href="#" id="upLine">上移</a> <a href="#" id="downLine">下移</a>
<table id="content" border="1">
<tr>
<th>序号</th><th>栏目</th><th>排序</th>
</tr>
</table>
<table border="1">
</table>
二.js代码:
<script language="javascript" src="jquery-1.3.2.js"></script>
<script language="javascript">
var currentStep=0; //当前行
var max_line_num=0;//最大行数
//添加一行
$("#addLine").click(function(){
max_line_num=$("#content tr:last-child").children("td").html();
if(max_line_num==null) {
max_line_num=1;
}
else{
max_line_num=parseInt(max_line_num);
max_line_num+=1;
}
$('#content').append("<tr id='line"+max_line_num+"' οnclick='lineclick(this);'><td>"+max_line_num+"</td><td>栏目"+max_line_num+"</td><td><select><option>升序</option><option>降序</option></select></td></tr>");
})
//删除一行
$("#removeLine").click(function(){
if(currentStep==0){
alert('请选择一项!');
return false;
}
$("#content tr").each(
function(){
var seq=parseInt($(this).children("td").html());
if(seq==currentStep) {$(this).remove();max_line_num--;/*最大行数*/}
if(seq>currentStep) $(this).children("td").each(function(i){
if(i==0){
$(this).html(seq-1);$(this).parent().attr("id","line"+(seq-1));//修改所在行的表示
}
});
}
);
currentStep=0;
})
//上移
$("#upLine").click(function(){
if(currentStep==0){
alert('请选择一项!');
return false;
}
if(currentStep<=1){
alert('已经是第一行!');
return false;
}
var upStep=currentStep-1;
//修改序号
$('#line'+upStep+" td:first-child").html(currentStep);
$('#line'+currentStep+" td:first-child").html(upStep);
//取得两行的内容
var upContent=$('#line'+upStep).html();
var currentContent=$('#line'+currentStep).html();
$('#line'+upStep).html(currentContent);
//交换当前行与上一行内容
$('#line'+currentStep).html(upContent);
$('#content tr').each(function(){$(this).css("background-color","#ffffff");});
$('#line'+upStep).css("background-color","yellow");
currentStep=upStep;
})
//下移
$("#downLine").click(function(){
if(currentStep==0){
alert('请选择一项!');
return false;
}
if(currentStep>=max_line_num){
alert('已经是最后一行!');
return false;
}
var nextStep=parseInt(currentStep)+1;
//修改序号
$('#line'+nextStep+" td:first-child").html(currentStep);
$('#line'+currentStep+" td:first-child").html(nextStep);
//取得两行的内容
var nextContent=$('#line'+nextStep).html();
var currentContent=$('#line'+currentStep).html();
$('#line'+nextStep).html(currentContent);
//交换当前行与上一行内容
$('#line'+currentStep).html(nextContent);
$('#content tr').each(function(){$(this).css("background-color","#ffffff");});
$('#line'+nextStep).css("background-color","yellow");
currentStep=nextStep;
})
//选中行
function lineclick(line){
$('#content tr').each(function(){$(this).css("background-color","#ffffff");});
var seq=$(line).children("td").html();
$(line).css("background-color","yellow");
currentStep=seq;
}
</script>
三.css代码:
<style type="text/css">
#content{border-collapse: collapse;}
#content tr td{width: 60px}
#content tr th{width: 60px}
#content tr td select{width: 60px}
</style>