简体   繁体   中英

Translate table in pure js

I've made a simple table in HTML, CSS andBootstrap , and I want to change the dates that are in the cells. (translate text)

<table class="table table-striped" id="TabelPret">
    <thead>
        <tr>
            <th scope="col">id</th>
            <th scope="col">service</th>
            <th scope="col">price(Euro)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">1</th>
            <td>consulting</td>
            <td>50</td>
        </tr>
        <tr>
            <th scope="row">2</th>
            <td>RECONSULT</td>
            <td>15</td>
        </tr>
        <tr>
            <th scope="row">3</th>
            <td>1 procedur/30 min</td>
            <td>10</td>
        </tr>                                            
    </tbody>
</table>
    

Now for JS, i try to select the table then to add new rows and colums:

var array = [
    ["a1", "b1", "c1"],
    ["a2", "b1", "c1"],
    ["a3", "b1", "c1"],
    ["a4", "b1", "c1"],
    ["a5", "b1", "c1"],
    ["a6", "b1", "c1"],
    ["a7", "b1", "c1"]
];

That array will be the new cells so ( a1 is translate for id, b1 is translate for consulting, c1 is translate for price...etc)

table = document.getElementById("TabelPret");
for (var i = 0; i < table.rows.length; i++) {
  for (var j = 0; i < table.rows[i].cells.length; j++) {
    table.rows[i].innerHTML = array[i][j];
  }
}

This code doesn't work for me, is there another option? Only in pure JavaScript, the table will be static.

Thanks for your help and time.

Try this in your loop to reference each cell and assign from your 2d array:

table.rows[i].cells[j].innerHTML = array[i][j];

Loop over the array instead and use document.createElement to create rows and cells to append to the tbody .

 const tbody = document.querySelector('table > tbody'); var array = [ ["a1", "b1", "c1"], ["a2", "b1", "c1"], ["a3", "b1", "c1"], ["a4", "b1", "c1"], ["a5", "b1", "c1"], ["a6", "b1", "c1"], ["a7", "b1", "c1"], ]; for (var i = 0; i < array.length; i++) { const row = document.createElement('tr'); for (var j = 0; j < array[i].length; j++) { const cell = document.createElement('td'); cell.textContent = array[i][j]; row.appendChild(cell); } tbody.appendChild(row); }
 <link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet"/> <table class="table table-striped" id="TabelPret"> <thead> <tr> <th scope="col">id</th> <th scope="col">service</th> <th scope="col">price(Euro)</th> </tr> </thead> <tbody> </tbody> </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