前言
網上看了很多基於bootstrap的table表格行內編輯,需要基於bootstrap-table,bootstrap-table-edit,x-editable等插件,寫的很復雜。
我想實現的需求很簡單,在頁面上寫個簡單的table表格,能刪除行,添加行,點擊每一個報告能直接編輯就行,不需要那些花里胡哨的功能。
最后還是自己基於bootstrap寫了一個table報告的在線編輯功能。
實現效果
想實現的效果如下圖所示:
- 1.點輸入框能占滿一格
- 2.最后一列添加刪除按鈕
- 3.可以點添加一行按鈕
前端實現
基於bootstrap框架
<html>
<head>
<title>table表格行內編輯</title>
<link href="/static/bootstarp/css/bootstrap.min.css" rel="stylesheet">
<script src="/static/bootstarp/jquery/jquery.min.js"></script>
<script src="/static/bootstarp/js/bootstrap.min.js"></script>
<script src="/static/bootstarp/jquery/jquery.serializejson.min.js"></script>
<style>
.table-condensed>tbody>tr>td {
padding: 0;
}
td input{
border: 0;
width:100%;
height: 27px;
font-size: 22px;
text-align: center;
background-color: rgba(0, 0, 0, 0);
}
td.operate{
text-align: center;
}
td.operate button{
margin: 2px;
}
tr th{
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<form id="form_table">
<table class="table table-striped table-bordered table-condensed">
<caption><button type="button" class="btn btn-info add_row">add headers</button></caption>
<thead>
<tr>
<th class="col-md-5 col-xs-5"><b>key</b></th>
<th class="col-md-5 col-xs-5"><b>value</b></th>
<th class="col-md-1 col-xs-2">操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input title="key" type="text" name="tab[][key]" value=""></td>
<td><input title="value" type="text" name="tab[][value]" value=""></td>
<td class="operate"><button type="button" class="btn btn-xs btn-danger del_row">刪除</button></td>
</tr>
</tbody>
</table>
<input type="button" id="save" class="btn btn-success" value="提交">
</form>
</div>
</body>
</html>
操作按鈕
添加一行按鈕實現,簡單粗暴直接append添加一行
// 添加一行
$(".add_row").click(function(){
var $tbody = $(this).parent().parent().find("tbody");
var tr = [
'<tr>',
'<td><input title="key" type="text" name="tab[][key]" value=""></td>',
'<td><input title="value" type="text" name="tab[][value]" value=""></td>',
'<td class="operate"><button type="button" class="btn btn-xs btn-danger del_row">刪除</button></td>',
'</tr>'
];
$tbody.append(tr.toString())
});
刪除按鈕實現
// 刪除一行
$(document).on('click','.del_row', function(){
$(this).parent().parent().remove();
});
最后提交數據
提交數據需獲取table報告上的輸入內容,希望是鍵值對的數據,於是可以用到form表單序列化,在table外層加一個form標簽。
使用jquery.serializejson.min.js
來序列化表單內容
// 獲取數據
$(document).on('click','#save', function(){
a = $("#form_table").serializeJSON();
console.log(JSON.stringify(a))
})
最終實現效果