jQuery如何动态添加索引号到表中

标签 jquery html-table auto-increment

我创建了一个表,当选中复选框时,我可以使用 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/

相关文章:

javascript - 用户输入2个数字,输出数字和表中的总和。正在输出,但不在表中?

html - 转发器表中的多行悬停

mysql - MySQL的AUTO_INCREMENT列如何重置

mysql - 奇怪的Mysql增量

javascript - 如果我要访问的 id 存储在变量中,我该如何访问元素

jquery - 弹出窗口关闭时停止youtube视频

应用 jQuery 后 php header 不起作用

javascript - 使用 jQuery/Javascript 单击时创建同一 Div 的多个随机实例?

html - 圆 table Angular 仅 CSS

asp.net - 将自动增量 ID 与 ASP.NET 复选框列表结合使用