java基礎5
阿新 • • 發佈:2021-02-01
技術標籤:JavaScriptjshtml
JavaScript實現table動態新增、刪除行
效果圖
點選 + 實現table新增一行,點選 - 刪除本行
HTML
<table id="file-tab">
<tr>
<td style="width : 500px">
<label class="layui-form-label" style="width : 100%; text-align: left"></label>
</ td>
<td>
<input type="file" style="width : 100%; display: none" onchange="updFilePath(this)">
<button type="button" class="layui-btn" style="width : 100%" onclick="selectFile(this)">選擇檔案</button>
</ td>
<td>
<button type="button" lay-filter="demo2" class="layui-btn layui-btn-del" lay-filter="demo2" style="margin-left : 10px" onclick="deleteCurrentRow(this)"> - </button>
</td>
</tr>
</table>
< button type="button" class="layui-btn layui-btn-sm" onclick="appendRow()" style="margin-top : 10px"> + </button>
JavaScript
var num = 1;
/* 新增行 */
function appendRow(){
var trHTML = '<tr>' +
'<td style="width : 500px">' +
'<label class="layui-form-label" style="width : 100%; text-align: left">'+(num++)+'</label>' +
'</td>' +
'<td>' +
'<input type="file" style="width : 100%; display: none" οnchange="updFilePath(this)">' +
'<button type="button" class="layui-btn" style="width : 100%" οnclick="selectFile(this)">選擇檔案</button>' +
'</td>' +
'<td>' +
'<button type="button" lay-filter="demo2" class="layui-btn layui-btn-del" lay-filter="demo2" style="margin-left : 10px" οnclick="deleteCurrentRow(this)"> - </button>' +
'</td>' +
'</tr>';
$("#file-tab").append(trHTML);
}
/* 刪除行 */
function deleteCurrentRow(obj) {
var tab=document.getElementById("file-tab");//獲取table物件
var tr = obj.parentElement.parentElement;//獲取obj所在行的物件
var rowIndex = tr.rowIndex;//獲取行號
tab.deleteRow(rowIndex);//刪除當前行
}