当前位置:   article > 正文

web table 表格动态添加以及数据解析_web实现动态表格

web实现动态表格

table 表格动态添加以及数据解析
工作中需要前端处理一个带表头的动态table,在实现的过程走了些弯路,现在把最终的处理点记录一下:
首先,html 下添加表格相关元素,参考如下:

 <div>
    <table style="width:100%;margin-top:24px;"class="myclass" id="mytable">
        <thead>
            <tr>
                <td width="10%">列名1</td>     //第一列
                <td width="30%">列名2</td>     //第二列
                <td width="30%">列名3</td>     //第三列
                 <td width="30%">列名4</td>     //第四列
            </tr>
        </thead>
        <tbody>
        /*tbody  先留白,动态添加*/
        </tbody>
    </table>
</div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

第二步,在相关的js 文件动态添加需要的表数据,处理函数参考如下:

//这里我们演示td 包含 span、select、input、button的几种情况
 function append_mytable_list(value1,value2,value3)
    {
        var u_info = '<tr>' +
        '<td "><span>' +value1+ '</span></td>' +
        '<td><select type="select" >'
		 u_info= u_info +'<option value='+value2+' selected>' + value2 + '</option></select></td>';
		 //在设置input数数据前对字符串去空格处理
		 var value3_real=value3.replace(/\s*/g,"");
        u_info =u_info +'<td><input value=' +value3_real+ '></input></td>' +
        '<td><button type="button"  class="btn_del delete  my_td_delete" role="button"></button>' +
        '</td></tr>';
        $("#mytable tbody").append(u_info);
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

获取table的数据项

 $('#mytable tbody tr').each(function ()
        {
            item.td1=$(this).find('td:eq(0) span').text();
            item.td2 =$(this).find('td:eq(1) select').val();
            item.td3=$(this).find('td:eq(2) input').val();
           ........
        })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

假设表格每行的最后的那个button项,点击可以删除整行,处理事件参考:

 $("body").on("click", ".biss_item_delete", function () {
 //假如需要获得本行的其它单元的值
    var value= $(this).parent().parent().find('span').text();
    $(this).parents("tr").remove();
  })
  • 1
  • 2
  • 3
  • 4
  • 5

还有一些比较实用的技巧:
如判断输入的是不是4个字节的16进制数:

var myreg = /^[0-9a-fA-F]{8}$/;
if(myreg.test(value3)==0)   
{
//不是的话,如何处理。。。
}
  • 1
  • 2
  • 3
  • 4
  • 5
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/724878
推荐阅读
相关标签
  

闽ICP备14008679号