gpt4 book ai didi

javascript - 使用 Javascript 和 jQuery 创建表

转载 作者:行者123 更新时间:2023-11-28 13:15:41 25 4
gpt4 key购买 nike

我正在尝试使用 Javascript 和 jQuery 创建动态表,但结果很困惑。你能告诉我我的代码有什么问题吗?

在下面您可以找到我的代码以及 JSFiddle 上的示例。

Here是代码,您可以自己尝试一下。

var students = [{
"name": "John Doe",
"friends": ["Tim", "Ann", "Lou", "Thomas", "Elias"]
}, {
"name": "Harry Potter",
"friends": ["Ron", "Hermione"]
}, {
"name": "James May",
"friends": ["Hammnond", "Richard"]
}];



for (var i = 0; i < students.length; i++) {
var student = students[i];
$('#table').append('<tr><td rowspan="' + student.friends.length + '">' + student.name + '</td>');

for (var u = 0; u < student.friends.length; u++) {
if (u == 0) {
$('#table').append('<td>' + student.friends[u] + '</td></tr>');
} else {
$('#table').append('<tr><td>' + student.friends[u] + '</td></tr>');
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
<h2>
Current Result
</h2>
<table id="table" border=1>
<tr>
<th>Name</th>
<th>Friends</th>
</tr>
</table>

<hr>
<h2>
Perfect Result
</h2>
<table border=1>
<tr>
<th>Name</th>
<th>Friends</th>
</tr>
<tr>
<td rowspan="5">John Doe</td>
<td>Tim</td>
</tr>
<tr>
<td>Ann</td>
</tr>
<tr>
<td>Lou</td>
</tr>
<tr>
<td>Thomas</td>
</tr>
<tr>
<td>Elias</td>
</tr>
<tr>
<td rowspan="2">Harry Potter</td>
<td>Ron</td>
</tr>
<tr>
<td>Hermione</td>
</tr>
<tr>
<td rowspan="2">James May</td>
<td>Hammond</td>
</tr>
<tr>
<td>Richard</td>
</tr>
</table>
</body>

最佳答案

This might solve your problem, Check this working fiddle https://jsfiddle.net/scgqwLp5/

JS

var students = [{
"name": "John Doe",
"friends": ["Tim", "Ann", "Lou", "Thomas", "Elias"]
}, {
"name": "Harry Potter",
"friends": ["Ron", "Hermione"]
}, {
"name": "James May",
"friends": ["Hammnond", "Richard"]
}];



for (var i = 0; i < students.length; i++) {
var student = students[i];
$('#table').append('<tr><td rowspan="' + (student.friends.length + 1) + '">' + student.name + '</td>');

for (var u = 0; u < student.friends.length; u++) {
$('#table').append('<tr><td>' + student.friends[u] + '</td></tr>');
}
}

HTML

<body>
<h2>
Current Result
</h2>
<table id="table" border=1>
<tr>
<th>Name</th>
<th>Friends</th>
</tr>
</table>

<hr>
<h2>
Perfect Result
</h2>
<table border=1>
<tr>
<th>Name</th>
<th>Friends</th>
</tr>
<tr>
<td rowspan="5">John Doe</td>
<td>Tim</td>
</tr>
<tr>
<td>Ann</td>
</tr>
<tr>
<td>Lou</td>
</tr>
<tr>
<td>Thomas</td>
</tr>
<tr>
<td>Elias</td>
</tr>
<tr>
<td rowspan="2">Harry Potter</td>
<td>Ron</td>
</tr>
<tr>
<td>Hermione</td>
</tr>
<tr>
<td rowspan="2">James May</td>
<td>Hammond</td>
</tr>
<tr>
<td>Richard</td>
</tr>

关于javascript - 使用 Javascript 和 jQuery 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38612974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com