2008年12月20日 星期六

jQuery Html table manipulation


  • Dynamic get the content of the table

  • JSON data(json.js):

    [{"AGE":"18","NAME":"Austin"},{"AGE":"20","NAME":"Leo"},{"AGE":"16","NAME":"Ting"}]

    You could visit JSON website for reference.
    Get ready for the skeleton.

    < table id="table1" width="200" border="1">
    < tr>
    < td width="30">& nbsp;< /td>
    < td width="100">Name< /td>
    < td>Age< /td>
    < /tr>
    < /table>

    Insert data:

    $.getJSON("./json.js",{},function(json){
    var i = 0;
    $.each(json, function(){
    $("#table1 tr:last").after(""+i+""+$(this).attr("NAME")+""+$(this).attr("AGE")+"");
    i++;
    });
    $("#table1").fadeIn("slow");
    });


  • Add New Row from First


  • $("#table1 tr:first").after('< tr>< td>& nbsp;< /td>< td>& nbsp;< /td>< td>& nbsp;< /td>< /tr>');


  • Add New Row from Last


  • $("#table1 tr:last").after('< tr>< td>& nbsp;< /td>< td>& nbsp;< /td>< td>& nbsp;< /td>< /tr>');


  • Remove Row from First


  • if($("#table1 tr").length == 1){
    alert("You can't delete it anymore!!");
    }else{
    $("#table1 tr:gt(0):first").remove();
    }


  • Remove Row from Last


  • if($("#table1 tr").length == 1){
    alert("You can't delete it anymore!!");
    }else{
    $("#table1 tr:last").remove();
    }


  • Change the Background of Row


  • $("#table1 tr:gt(0):odd").css({background:"#DDDDDD"});
    $("#table1 tr:gt(0):even").css({background:"#FFFFFF"});

沒有留言: