我已经创建了一个表并可以使用jQuery在选中复选框时添加和删除行。我的问题是,如何动态地在第一列添加一个索引号?
我的表格:
<div>
<table class="config" id="status_table">
<thead>
<tr>
<th colspan="4"; style= "padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em">Output Status</th>
</tr>
<tr>
<th>Index</th>
<th>Output Type</th>
<th>Output Number</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td >1</td>
<td ><p id="type_row_one"></p></td>
<td ><p id="number_row_one"></p></td>
<td>
<img class="image" id = "off" style="margin-left:20px" src="static/OffLamp-icon.png" >
<img class="image" id = "on" style="margin-left:20px" src="static/OnLamp-icon.png" >
</td>
</tr>
</tbody>
</table>
</div>
我的jQuery:
$('#outputCB').change(function(){
if($('#outputCB_1').is(':checked')){
$('#status_table tr:last').after('<tr id="output_newrow_1"><td>index+1</td><td>testing</td></tr>');}
else{
$('#status_table').find("#output_newrow_1").remove();
}
});
因此,我希望它不是简单的"index+1"
,而是能够从上一个索引号递增,并在删除行时递减。我该如何处理?在JavaScript中可以分配一个变量并执行++1或--1吗?我真的不知道从哪里开始......
更新:
我尝试了这个但失败了:
var index=1;
$('#outputCB').change(function(){
if($('#outputCB_1' ||'#outputCB_2').is(':checked')){
index++;
$('#status_table tr:last').after('<tr id="output_newrow_'+index+'"><td>'+index+'</td><td id="type_row_'+index+'">type_row_'+index+'</td><td id="num_row_'+index+'">num row '+index+'</td><td><img class="image" src="static/OffLamp-icon.png" style="height:64px; width=64px"/></td></tr>');
}
else{
index--;
$('#status_table').find("#output_newrow_'+index+'").remove();
}
});
当再次选中 #outputCB_1 时,它永远不会删除任何内容,并且每次添加两行。:/ 为什么呢?(抱歉,这个评论太长了。)