增删表格·
2018-07-20 本文已影响0人
酒暖花深Q
html
1.引入bootstrap
<link rel="stylesheet" href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<table class="table table-bordered text-center">
<tr>
<td>书名</td>
<td>作者</td>
<td>价格</td>
</tr>
<tr>
<td>红玫瑰与白玫瑰</td>
<td>张爱玲</td>
<td>¥23.5</td>
</tr>
<tr>
<td>你若安好,便是晴天</td>
<td>安意如</td>
<td>¥33.5</td>
</tr>
<tr>
<td>人生若只如初见</td>
<td>纳兰容若</td>
<td>¥24.5</td>
</tr>
</table>
<button>增加一行</button>
<button>删除一行</button>
<button>复制一行</button>
<button>改变标题样式</button>
<button>
<input type="text" placeholder="删除第几行" id="input">
<span style="border: 1px solid red" >删除</span>
</button>
js
var tr = document.getElementsByTagName("tr");
var btn = document.getElementsByTagName("button");
var tb = document.getElementsByTagName("tbody")[0];
var span = document.getElementsByTagName("span")[0];
btn[0].onclick = function(){
var tr1 = document.createElement("tr");
tr1.innerHTML = "<td>人生若只如初见</td><td>纳兰容若</td><td>¥24.5</td>";
// tb.appendChild(tr1); /*在tb的后面添加*/
tb.insertBefore(tr1,tr[1]);/*在已存在的tr[1]前面插入tr1*/
console.log(tr1.innerHTML);
};
btn[1].onclick = function(){
tb.removeChild(tr[tr.length -1]);//删除最后一行 tr的长度减一
};
btn[2].onclick =function () {
var tr2 = tr[tr.length-2].cloneNode(true);
tb.appendChild(tr2);
};
btn[3].onclick =function () {
tr[0].style.backgroundColor = "red"
};
span.onclick = function () {
var inp =document.getElementById("input").value;
var inp1 = parseInt(inp); /*对inp取整作为tr的值*/
tb.removeChild(tr[inp1]);
}
1.png