Jquery实现表格行的添加、删除
16lz
2021-01-22
最近做一个投票管理的模块,需要添加问题选项,为了方便,就简单地实现了表格行的添加、删除。
注:需引入jquery.js
先上效果图:(form中默认有4行)
表单代码:
<div class="oz-form-fields" style="width:450px;padding-top: 5px">
<table cellpadding="0" cellspacing="0" style="width:450px;" id="optionContainer">
<tr id="option0">
<td class="oz-form-topLabel">所属问题
<c:if test="${questionType=='radio'}">(单选)</c:if>
<c:if test="${questionType=='checkbox'}">(复选)</c:if>:
</td>
<td class="oz-property" >
${question}
</td>
<td></td>
</tr>
<tr id="option1">
<td class="oz-form-topLabel">选项1:</td>
<td class="oz-property" >
<input type="text" style="width:300px">
</td>
<td></td>
</tr>
<tr id="option2">
<td class="oz-form-topLabel">选项2:</td>
<td class="oz-property" >
<input type="text" style="width:300px" >
</td>
<td></td>
</tr>
<tr id="option3">
<td class="oz-form-topLabel">选项3:</td>
<td class="oz-property" >
<input type="text" style="width:300px">
</td>
<td></td>
</tr>
<tr id="option4">
<td class="oz-form-topLabel">选项4:</td>
<td class="oz-property" >
<input type="text" style="width:300px">
</td>
<td></td>
</tr>
</table>
<div style="text-align: center;">
<a href="#" onclick="addRow()">添加一行</a>
</div>
</div>
var rowCount=4; //行数默认4行
//添加行
function addRow(){
rowCount++;
var newRow='<tr id="option'+rowCount+'"><td class="oz-form-topLabel">选项'+rowCount+':</td><td class="oz-property" ><input type="text" style="width:300px"></td><td><a href="#" onclick=delRow('+rowCount+')>删除</a></td></tr>';
$('#optionContainer').append(newRow);
}
//删除行
function delRow(rowIndex){
$("#option"+rowIndex).remove();
rowCount--;
}
JS中要定义一个行数变量,因为我的表单中默认了4行(第一行,即id='option0'这行可以不用管),所以JS中定义的rowCount默认为4.
OK,完事。就如此的简单。
更多相关文章
- 未捕获的ReferenceError:HTML未在HTMLTableRowElement.onclick中
- 关于jQuery获取html标签自定义属性值或data值
- 在Chrome中使用AJAX发送选项而不是GET/POST/PUT/DELETE?
- jquery.validate.js使用之自定义表单验证规则
- jquery不会对select/选项更改事件作出反应。
- jquery自定义事件
- jQuery 三级联动选项栏
- 如何在使用jquery验证和自定义错误放置时清除错误
- 没有定义ReferenceError jquery - 仅限firefox