jQuery实现报表行的动态增加与删除(改进版)

jQuery实现表格行的动态增加与删除(改进版)
http://www.blogjava.net/absolutedo/archive/2009/03/13/259488.html



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <script src="jquery.js"></script>
    <script>
        $(function(){
            $(document.body).append("" +
                    "<table id='tab' border='1' width='60%' align='center' style='margin-top:20px'>\
                        <tr>\
                            <td width='20%'>序号</td>\
                            <td>操作</td>\
                        </tr>\
                    </table>");
            $("#but").click(function(){
                var length=$("#tab tr").length;
                $("#tab").append("<tr id=tab"+length+"><td>"+length+"</td><td><input type='button' value='删除' onclick='removeLine("+length+");'></td></tr>");
            });
        })
        function removeLine(index){
            var length=$("#tab tr").length;
            $("#tab"+index).remove();
            for(var i=index+1;i<=length;i++){
                $("#tab"+i).replaceWith("<tr id=tab"+(i-1)+"><td>"+(i-1)+"</td><td><input type='button' value='删除' onclick='removeLine("+(i-1)+");'></td></tr>");
            }
        }
    </script>
</head>
<body>

<!--<table id="tab" border="1" width="60%" align="center" style="margin-top:20px">
    <tr>
        <td width="20%">序号</td>
        <td>操作</td>
    </tr>
</table>-->
<div style="border:2px;border-color:#00CC00;margin-left:20%; margin-top:20px">
    <input type="button" id="but" value="增加"/>
</div>
</body>
</html>