实现方式一:只在最后一个数据中动态添加或者删除
| 背景
需要做一个页面,页面可以输入参数,点击确认按钮可以发请求给某接口。但是接口的某个字段是数组类型,所以在页面上需要实现添加或者删除元素的功能。| 实现
| html前端是基于bootstrap4.0.<form id="form" role="form" method="post" class="custom-control">
<div class="form-inline"> <label for="details" class="custom-control-label col-md-2">还款明细</label> <button type="button" class="button btn-light" id="add-btn" οnclick="add_div()">添加明细</button> <button type="button" class="button btn-light" id="del-btn" οnclick="del_div()">删除明细</button> </div> <div class="form-group" id="details"> <div class="form-inline"> <label for="receivable" class="custom-control-label col-md-3">应收金额</label> <input type="text" class="form-control" id="receivable" value="" placeholder="应收金额 单位分"/> </div> <div class="form-inline"> <label for="period" class="custom-control-label col-md-3">还款期数</label> <input type="text" class="form-control" id="period" value="" placeholder="还款期数"/> </div> <div class="form-inline"> <label for="kind" class="custom-control-label col-md-3">还款科目</label> <input type="text" class="form-control" id="kind" value="" placeholder="还款科目"/> </div> </div> </form>|JS<script type="text/javascript"> var detail_div = 1; function add_div() { var e = document.getElementById("details"); var div = document.createElement("div"); div.className = "form-group"; div.id = "details" + detail_div; div.innerHTML = e.innerHTML; document.getElementById("form").appendChild(div); detail_div++; }function del_div() {
var id = "details" + (detail_div - 1).toString(); var e = document.getElementById(id); document.getElementById("form").removeChild(e); detail_div--; }</script>效果如图
实现方式二:只在最后一个数据中动态添加,删除任意一个节点
html代码
js代码