简体   繁体   English

用纯js翻译表格

[英]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.我在 HTML、CSS 和Bootstrap中制作了一个简单的表格,我想更改单元格中的日期。 (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:现在对于 JS,我尝试 select 表然后添加新的行和列:

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)该数组将是新的单元格,所以( a1是为 id 翻译, b1是为咨询而翻译, c1是为价格翻译......等等)

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.只有在纯 JavaScript 中,表才会是 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 .而是循环遍历数组并使用document.createElement将行和单元格创建到 append 到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>

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

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