使用JavaScript更新表行索引

时间:2016-06-26 07:11:16

标签: javascript

我希望在删除行时更新表行号。如何使用现有代码执行此操作?以下是我的代码。 https://jsfiddle.net/arminemash/dkg6dnf6/2/

 <body onload="setTimeout('myFunction()', 500)">
  <div>
    <table id="myTable" border='1px'>
         <tr>
            <th>N</th>
            <th>Name</th>
            <th>Surname</th>
            <th>tel.</th>
            <th>email</th>
        </tr>
        <tr> 
            <td><button>add</button></td>
        </tr>
    </table>    
</div>
</body>

var arr=[['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],  ['m','n','o','p'],['q','r','s','t'],['u','v','w','x']];

function myFunction() {
  createTable();  
}

function createTable(){
  var i,j,row;
    var table = document.getElementById("myTable");
    for( i=1; i<arr.length; i++ ){
         row = table.insertRow(i);
         for( j=0; j<6; j++ ){
           var cell = row.insertCell(j);    
       }    
        table.rows[i].cells[0].innerHTML=i;
        table.rows[i].cells[5].innerHTML='<input type="button" value="delete" onclick="deleteRow(this)">';  
     }   
  }

 function deleteRow(r) {
     var i = r.parentNode.parentNode.rowIndex;
     document.getElementById("myTable").deleteRow(i);
 }

1 个答案:

答案 0 :(得分:0)

我会选择CSS解决方案。 只需将其添加到您的CSS:

table {
    counter-reset: rowNumber;
}

table tr:not(:first-child){
    counter-increment: rowNumber;
}

table tr td:first-child::before {
    content: counter(rowNumber);
    min-width: 1em;
    margin-right: 0.5em;
}

以下是链接:Fiddle link

干净的解决方案:https://jsfiddle.net/jLe2wggx/