一般来说,新增数据模态框和修改数据模态框几乎是完全一样的模态框,因为新增不需要数据回填,而修改数据需要,但这并影响它们共用一个模态框,唯一影响的是保存按钮,如果你给保存按钮一个点击事件触发调用一个方法,那么因为新增数据保存方法和修改数据保存方法是不同的,所以如果想它们共用一个模态框就必须要解决这个问题,然而保存按钮只能有一个点击事件,那么我们怎么可以实现一个点击事件去根据不同的情况去执行新增数据保存或者是修改数据保存操作呢?我们都知道新增数据是没有主键ID的参与的,因为在数据还没有新增成功,它的主键ID但是不存在的,当你保存成功后才会在数据库中数据库自身自增一个主键ID,然而修改数据不一样,修改数据是有主键ID的,而且我们可能还需要主键ID到数据库中查询回填的数据,根据主键ID是否存在这个条件我们可以想象一下,既然有这个条件,那么就可以根据这个条件去判断保存按钮执行的应该是新增数据保存操作还是修改数据保存操作,那么我们就可以在保存按钮点击事件里调用的方法里通过一个判断条件去执行不同的操作
注意:在修改保存方法里面一定要在提交数据方法的回掉函数里面在执行关闭模态框时也要把主键ID清空,如 $("#employeeID").val("");,注意确保在没有数据回填前主键ID都保存为空
给保存按钮一个onclick点击事件调用方法savaInsert()
<button type="button" class="btn
btn-outline-success mr-3" onclick ="savaInsert()">保存</button>
4.在savaInsert()方法里通过判断条件执行不同的方法
function savaInsert() {
var employeeID = $("#employeeID").val();//获取主键ID
if (employeeID > 0)
{
savaInsert2();//执行调用修改数据保存方法
}else{
savaInsert1();//执行调用新增数据保存方法
}
}
5.模态框
<div class="modal
fade" id="modalEmployee" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
新增员工
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="formEmployee" class="form-horizontal">
<!--重置表单-->
<input type="reset" hidden />
<input type="hidden" id="employeeID" name="employeeID" />
<div class="form-group
form-row">
<label class="col-form-label
col-3" for="employeeNum">员工编号:</label>
<div class="col-9">
<input type="text" class="form-control" name="employeeNum" id="employeeNum" />
</div>
</div>
<div class="form-group
form-row">
<label class="col-form-label
col-3" for="employeeName">员工姓名:</label>
<div class="col-9">
<input type="text" class="form-control" name="employeeName" id="employeeName" />
</div>
</div>
<div class="form-group
form-row">
<label class="col-form-label
col-3" for="telphone">联系电话:</label>
<div class="col-9">
<input type="text" class="form-control" name="telphone" id="telphone" />
</div>
</div>
<div class="form-group
form-row">
<label class="col-form-label
col-3" for="address">家庭地址:</label>
<div class="col-9">
<input type="text" class="form-control" name="address" id="address" />
</div>
</div>
<div class="form-group
form-row justify-content-center">
<div class="col-4">
<button type="button" class="btn
btn-outline-success mr-3" onclick="savaInsert()">保存</button>
<button type="button" class="btn
btn-outline-secondary " data-dismiss="modal">关闭</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>