简体   繁体   English

如何使用jquery / javascript为html中的ID列生成并分配唯一编号

[英]How to generate and assign unique number for an ID column in html using jquery/javascript

At id column I need to add auto generated ID value dynamivcally when I added a new row 在id列中,我需要在添加新行时动态添加自动生成的ID值

<table>
<tr>
    <th>Employee Id</th>
    <th>Employee Name</th>
    <th>Salary</th>
    <th>Email</th>              
</tr>
<tr>
   <td ></td>// for id
   <td><input type="text" id="new_name"></td>
   <td><input type="text" id="new_salary"></td>
   <td><input type="text" id="new_email"></td>
</tr>

</table>

One possible solution is to declare a counter variable to keep track of how many rows have been generated. 一种可能的解决方案是声明一个计数器变量以跟踪已生成的行数。 Then when you append a new row, you can set it's id attribute to this variable. 然后,当您添加新行时,可以将其id属性设置为此变量。

 var index = 1; $("#new-row").on("click", function() { var name = $("#new_name").val(); var salary = $("#new_salary").val(); var email = $("#new_email").val(); $("table").html($("table").html() + "<tr id='row" + index + "'><td>" + index + "<td>" + name + "</td><td>" + salary + "</td><td>" + email + "</td></tr>"); index++; }); 
 #row1 { background: red; } #row2 { background: orange; } #row3 { background: yellow; } td { text-align: center; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <th>Employee Id</th> <th>Employee Name</th> <th>Salary</th> <th>Email</th> </tr> <tr> <td ></td>// for id <td><input type="text" id="new_name"></td> <td><input type="text" id="new_salary"></td> <td><input type="text" id="new_email"></td> </tr> </table> <button id="new-row">Generate new row</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM