简体   繁体   中英

Edit a table with Jquery find() then add cell with data from an array with before()

I am trying to insert a column of cells with data from an array. I have tried using a for loop, but that just put all the data of the array in each new cell. My goal is to have the new cells display row_header1, row_header2, or row_header3 respectively.
Can anyone help me with this issue? Thank you.

-for loop I'vs tried.

for (var i = 0, len = arr1.length; i < len; i++) {
      $("tr").find("td:first").before('<td>' + arr1[i] + '</td>')

 var arr1 = ["row_header1", "row_header2", "row_header3"]; $(document).ready(function() { $("#btn").click(function() { var i = 0, len = arr1.length; i < len; i++; $("tr").find("td:first").before('<td>' + arr1[i] + '</td>') }); });
 td, th { padding: 4px; border: solid; width: 50px; height: 50px; } table { border-collapse: collapse; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="btn">+</button> <table id='table'> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> </table>

I think you need to select the right tr each time when you want to assign value

 var arr1 = ["row_header1", "row_header2", "row_header3"]; $(document).ready(function() { $("#btn").click(function() { var i = 0, len = arr1.length; while(i< len){ $("tr:eq("+i+")").find("td:first").before('<td>' + arr1[i] + '</td>'); i++; } }); });
 td, th { padding: 4px; border: solid; width: 50px; height: 50px; } table { border-collapse: collapse; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="btn">+</button> <table id='table'> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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