我有json stu,其中包含学生姓名和部门我有一个html表,其中包含stuent名称和部门作为标题和表ID作为学生我用于在表中添加数据但数据在一个列中添加为空专栏我是json的新手,任何人都可以帮忙
<!DOCTYPE html>
<html>
<head>
<title>JSON Demo</title>
<style>
table,th,td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="button" onClick="StudentDetails()" value="Student Table" />
<div>
<table id="student">
<thead>
<tr>
<th>Student Name</th>
<th>Student Department</th>
</tr>
<thead>
<tbody></tbody>
</table>
</div>
<script>
function StudentDetails() {
var stu = [{
"stuname": "anbu",
"studep": "cs"
},
{
"stuname": "raj",
"studep": "Maths"
},
{
"stuname": "mani",
"studep": "science"
}
]
var table='<student>';
$.each(stu, function(i, item){
table+='<tr><td>'+item.stuname+'</td></tr>';
table+='<tr><td>'+item.studep+'</td></tr>';
});
$("#student").append(table);
console.log(table);
}
</script>
</body>
</html>
答案 0 :(得分:1)
您的功能存在严重的逻辑问题。我解决了这个问题。
你需要做的是将html附加到表格中,你正在做的不是正确的做法。
<!DOCTYPE html>
<html>
<head>
<title>JSON Demo</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="button" onClick="StudentDetails()" value="Student Table" />
<div>
<table id="student">
<thead>
<tr>
<th>Student Name</th>
<th>Student Department</th>
</tr>
<thead>
<tbody></tbody>
</table>
</div>
<script>
function StudentDetails() {
var stu = [{
"stuname": "anbu",
"studep": "cs"
},
{
"stuname": "raj",
"studep": "Maths"
},
{
"stuname": "mani",
"studep": "science"
}
]
var table = '';
$.each(stu, function(i, item) {
table += '<tr><td>' + item.stuname + '</td><td>' + item.studep + '</td></tr>';
});
$("#student tbody").append(table);
console.log(table);
}
</script>
</body>
</html>