在js里面,经常需要使用js往页面中插入html内容,常用append方法
$('#div1').append('<div>你好</div>')
如果内容过多的话会拼接繁杂,不方便编码,也有局限性。
template简单使用
<script type='text/template' id=" templateChild ">较为方便
var templateChild = $($("#templateChild").html()).clone();
$("#childEnterprisesTbody").append($(templateChild));
如果是添加表单中表格一些数据势必会需要提交数据,如:project[0].name,project[0].id,project[1].name,project[1].id等表格新增行就会遇到下标是几的问题,这里需要格式化新增行input中name=“project[0].id”的下标。
解决方法如下:
模板上我们给下标为?符号,我们添加行的时候通过js排序并替换?为正确下标1、2、3…
<script type="text/template" id="templateChild">
<tr style="text-align: center;">
<td>
<input type="hidden" name="subsidiaryCompany[?].businessId" value="${enterprise.mainEnterpriseId}" />
<input type="text" name="subsidiaryCompany[?].name" value="${business.name}" required maxlength="200" lay-verify="required" placeholder="请输入公司名称" autocomplete="off" class="layui-input">
</td>
<td align="center">
<button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="delChild(this)">删除</button>
</td>
</tr>
</script>
表格数据加载实例
<button type="button" class="layui-btn layui-btn-xs layui-btn-normal f-right" onclick="addChild()">添加</button>
<table class="layui-table f-table-fixed small" lay-size="sm">
<colgroup>
<col width="300">
<col width="100">
</colgroup>
<thead>
<tr>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody class="f-p-n" id="childEnterprisesTbody">
<c:forEach items="${subsidiaryCompany }" var="business" varStatus="i">
<tr style="text-align: center;">
<td>
<input type="hidden" name="subsidiaryCompany[${i.index}].id" value="${business.id}" />
<input type="hidden" name="subsidiaryCompany[${i.index}].businessId" value="${business.businessId}" />
<input type="text" name="subsidiaryCompany[${i.index}].name" value="${business.name}" required maxlength="200" lay-verify="required" placeholder="请输入公司名称" autocomplete="off" class="layui-input">
</td>
<td align="center">
<button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="delChild(this)">删除</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
Js代码
//添加子公司
function addChild() {
var templateChild = $($("#templateChild").html()).clone();
$("#childEnterprisesTbody").append($(templateChild));
orderChild();
}
/**
* 排序子公司
*/
function orderChild() {
$("#childEnterprisesTbody").find("tr").each(function(i) {
$(this).find("[name^='subsidiaryCompany']").each(function(j) {
var nameStr = $(this).attr("name");
var newName = nameStr.replace(/\?|\d+/, i);
$(this).attr("name", newName);
});
});
}
//删除子公司
function delChild(_this) {
$(_this).parent().parent().remove();
orderChild();
}