1. 程式人生 > >jquery實現table動態新增行、刪除行以及行的上移和下移

jquery實現table動態新增行、刪除行以及行的上移和下移

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function($){
    //元素交換  
    $(".up").live('click',function(){  
        $(this).parent().parent().prev("tr").before($(this).parent().parent());  
    });  
    $(".down").live('click',function(){  
        $(this).parent().parent().next("tr").after($(this).parent().parent());  
    });  
      
    $(".delete").live('click',function(){  
        $(this).parent().parent().remove();  
    });  
      
    $(".add").live('click',function(){  
        var i= $("#tr_count").val();
        $('<tr id="'+(i++)+'"><td>'+(i)+'</td><td><input type ="button" value="上" class="up"/><input type ="button" value="下" class="down"/><input type ="button" value="刪" class="delete"/><input type ="button" value="加" class="add"/></td></tr>')  
        .insertAfter($(this).parent().parent());  
        $("#tr_count").val(i);

    });  




});
</script>


</head>
<body>

<input type="hidden" value="1" id="tr_count">
<table width="100" height="100" id="table" border="1">  
    <tr id="1">  
        <td>1</td><td>  
        <input class="up" type="button" value="上">  
        <input class="down" type="button" value="下">  
        <input class="delete" type="button" value="刪">  
        <input class="add" type="button" value="加">  
        </td>  
    </tr>  
</table>

</body>
</html>