简体   繁体   English

使用javascript将数据插入到HTML表格中

[英]Insert data into an HTML table using javascript

I have the following HTML table with 5 rows and 5 columns (table.html).我有以下 5 行 5 列的 HTML 表格 (table.html)。 I need to insert letter 'A' on each cell.我需要在每个单元格上插入字母“A”。 How do I achieve this using javascript?我如何使用 javascript 实现这一目标?

If you are usin jQuery.如果您使用 jQuery。 It is very simple这很简单

$('td').each(function(){
   $(this).html('A' + $(this).html());
});

Using only JavaScript (no jQuery):仅使用 JavaScript(无 jQuery):

JavaScript JavaScript

var cells = document.getElementsByTagName("td");

for(var i = 0; i < cells.length; i++){
    var cell = cells[i];
    cell.innerText = "A " + cell.innerText;
}

JSFiddle JSFiddle

EDIT编辑

If you want to target a specific table, you can do this by setting an id on it and using something like this:如果你想定位一个特定的表,你可以通过在它上面设置一个 id 并使用这样的东西来做到这一点:

var cells = document.getElementById("a-table").getElementsByTagName("td");

JSFiddle JSFiddle

Try this, using the selector that suits you, for example:试试这个,使用适合你的选择器,例如:

[].forEach.call(document.querySelectorAll("#table_id td"), function(el){
    el.innerHTML = 'A';
});

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

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