用js实现动态添加表格数据

用js实现动态添加表格数据,第1张

1、在页面div中事先创建一个空白表格,可以根据需求而定。

2、表格创建好后,我们就可以写动态生成表格的关键代码了。我们写一个js方法供触发使用。

3、在<tb>标签中我们添加了<input>标签,主要是用来提供用户输入参数, 而全局变量num,主要是用来区分每一个添加的参数的id的唯一性而存在的。

4、获得表格中的数据。

5、拿到表格中的数据后,我们根据它值的形式把它转换成json格式的数据。

setAttribute("width","200")设置属性

setAttribute("属性名","属性值")

用insertRow()添加行

insertCell()添加列

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">

<title>增加Table行</title>

</head>

<script>

function addRow(obj)

{

//添加一行

var newTr = testTbl.insertRow()

//添加两列

var newTd0 = newTr.insertCell()

var newTd1 = newTr.insertCell()

//设置列内容和属性

newTd0.innerHTML = '<input type=checkbox id="box4">'

newTd1.innerText= '新加行'

}

</script>

<body>

<table id="testTbl" border=1>

<tr id="tr1">

<td ><input type=checkbox id="box1"></td>

<td id="b">第一行</td>

</tr>

<tr id="tr2">

<td ><input type=checkbox id="box2"></td>

<td id="b">第二行</td>

</tr>

<tr id="tr3">

<td ><input type=checkbox id="box3"></td>

<td>第三行</td>

</tr>

</table>

<br />

<input type="button" id="add" onClick="addRow()" value="Add Row" />

</body>

标准的表格 *** 作,并没有 innerCell() 的,innerRow 是添加一行,innerCell 只在部分浏览器中可以实现,不过现在大部分都支持 innerCell()

<!DOCTYPE HTML>

<html> 

<body>

    <table>

        <tbody id="tab">

        

        </tbody>

    </table>

</body>

</html> <script type="text/javascript">

    window.onload = function() {

        // 为 id = tab 的控件添加一行 <tr></tr>

        var row = tab.insertRow(-1)

        // 创建 th 列

        var cell_0 = document.createElement("th")

        // 设置他的 scope 属性为 row,设置他的 innerHTML 为 title

        cell_0.setAttribute("scope", "row")

        cell_0.innerHTML = "title"

        var cell_1 = document.createElement("th")

        cell_1.setAttribute("scope", "row")

        cell_1.innerHTML = "name"

        

        // 把创建好的 cell_0 和 cell_1 添加到 行中

        row.appendChild(cell_0)

        row.appendChild(cell_1)

        // 打印出当前 id=tab 的内容,可以看到, <tr><th scope="row">title</th><th scope="row">name</th></tr>

        alert(tab.innerHTML)

    }

</script>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11933006.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存