分享

原生js动态实现添加表格数据并某列求和

 hncdman 2023-03-08 发布于湖南

@Frederick

于 2019-05-29 15:02:16 发布

5792

 收藏 7

分类专栏: javascript 文章标签: javascript

版权

javascript

专栏收录该内容

1 篇文章0 订阅

订阅专栏

   <table width="600" border="1" cellspacing="0">

         <thead>

             <tr>

               <th>编号</th>

               <th>姓名</th>

  <th>职位</th>

  <th>年龄</th>

  <th>操作</th>

</tr>`

</thead>

         <tbody id="tbMain"></tbody>

         <tfoot id="tdfoot"> 

<tr>

               <th></th>

               <th></th>

  <th>合计</th>

  <th></th>

  <th></th>

</tr>

</tfoot>

   </table>

<script type="text/javascript">

    //模拟一段JSON数据,实际要从数据库中读取

var per = [

{id:001,name:"张三",job:"学生",age:14},

     {id:002,name:"李四",job:"教师",age:34},   

     {id:003,name:"王五",job:"经理",age:44}

];

    window.onload = function(){

      var tbody = document.getElementById("tbMain");

      for(var i =0; i<per.length; i++){ //遍历一下json数据

         var trow  = getDataRow(per[i]);  //定义一个方法,返回tr数据

         tbody.appendChild(trow);

 }

     //年龄求和

      var calcTotal = function (table,column){

var trs = table.getElementsByTagName('tr');

//alert(trs.length);

var total = 0;

for(var i = 0; i < trs.length; i++){

           var td = trs[i].getElementsByTagName('td')[column];

  var t = parseFloat(td.innerHTML);

           if(t)total+=t;

}

document.getElementById("tdfoot").getElementsByTagName('th')[column].innerHTML = total;

};

      calcTotal(document.getElementById('tbMain'),3);

}

   function getDataRow(h){

    var row = document.createElement("tr"); //创建行

var idCell = document.createElement("td"); //创建列

idCell.innerHTML = h.id;//填充数据

row.appendChild(idCell);//加入行,一下类似

var nameCell = document.createElement("td");

nameCell.innerHTML = h.name;

    row.appendChild(nameCell);

    var jobCell = document.createElement("td");

    jobCell.innerHTML = h.job;

row.appendChild(jobCell);

var ageCell = document.createElement("td");

    ageCell.innerHTML = h.age;

row.appendChild(ageCell);

    var delCell = document.createElement("td");

    row.appendChild(delCell);

var btnDel = document.createElement("input");//创建一个input控件

     btnDel.setAttribute('type','button');//type="button"  

btnDel.setAttribute('value','删除');

   //删除操作

btnDel.onclick = function(){

      if(confirm("确定删除这一行吗?")){

      //找到按钮所在行的节点,然后删掉这一行  

         this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);

 }

}

delCell.appendChild(btnDel);

     return row;//返回tr数据

   }

</script>

————————————————

版权声明:本文为CSDN博主「@Frederick」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多