我在Json数组中有类似的字段
[
{
"id": 1,
"name": "test",
"last_name": "test",
},
{
"id": 2,
"name": "test1",
"last_name": "test1",
},
{
"id": 2,
"name": "test2",
"last_name": "test2",
}
]
Run Code Online (Sandbox Code Playgroud)
如何使用带有列id,名称,姓氏的jquery创建html表?
var json = [Your JSON here];
var $table = $('<table/>');
$.each(json, function(index, value) {
//create a row
var $row = $('<tr/>');
//create the id column
$('<td/>').text(value.id).appendTo($row);
//create name column
$('<td/>').text(value.name).appendTo($row);
//create last_name
$('<td/>').text(value.last_name).appendTo($row);
$table.append($row);
});
//append table to the body
$('body').append($table);
Run Code Online (Sandbox Code Playgroud)
请注意,这不会创建标题行,但您可以以相同的方式轻松完成此操作.
编辑:这里不需要jQuery:
var json = [Your JSON here],
table = document.createElement('table');
for(var i = 0, il = json.length; i < il; ++i) {
//create row
var row = document.createElement('tr'),
td;
//create the id column
td = document.createElement('td');
td.appendChild(document.createTextNode(json[i].id));
row.appendChild(td);
//create name column
td = document.createElement('td');
td.appendChild(document.createTextNode(json[i].name));
row.appendChild(td);
//create last_name column
td = document.createElement('td');
td.appendChild(document.createTextNode(json[i].last_name));
row.appendChild(td);
table.appendChild(row);
}
document.body.appendChild(table);
Run Code Online (Sandbox Code Playgroud)
显然你可以把它清理干净,但是你明白了.