我创建了一个表,当选中复选框时,我可以使用 jQuery 添加和删除行。我的问题是,如何在第一列动态添加索引号?
我的 table :
<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 时它会一次添加 2 行。 :/为什么这样? (抱歉,评论太长了。)
最佳答案
每次添加或删除行时调用此代码
function updateIndex()
{
$("#status_table tr").each(function(){
$( this ).find( "td" ).first().html( $(this).index() + 1 );
});
}
关于jQuery如何动态添加索引号到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16097519/