我有两个数组的数据。我的数据如下:
var inputArray:[Any] = [1,[4,3],6,[5,[1,0]]]
我希望我的表的行数与cats中的元素相同,而列数与dogs中的元素相同。这是我到目前为止的内容:
var cats = [ "a", "b", "c", "d", "e", "f"];
var dogs = [ "z", "y", "x", "w"]
我无法显示静止画面
答案 0 :(得分:0)
欢迎使用堆栈溢出。你快到了。每次进入外部循环时,您都需要添加一个新的tr
。查看我的代码段。
免责声明:破旧的代码质量。请不要判断我!
var cats = [ "a", "b", "c", "d", "e", "f"];
var dogs = [ "z", "y", "x", "w"]
var str = '';
for(let cat of cats) {
str = '<tr>';
for(let dog of dogs) {
str += '<td>'+cat+' '+dog+'</td>';
}
str += '</tr>';
$("#mytable").append( str );
}
td {
border: 1px solid #ddd;
padding: 4px 6px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tabld id = "mytable">
</table>
答案 1 :(得分:0)
您的代码中有一些语法错误。
固定的HTML:
<table id="mytable">
<tr>
<td> Cats/dogs</td>
</tr>
</table>
固定的JS: var cats = [“ a”,“ b”,“ c”,“ d”,“ e”,“ f”]; var dogs = [“ z”,“ y”,“ x”,“ w”];
var numberOfRows = cats.length;
var numberOfColumns = dogs.length;
for (var i = 0; i < numberOfRows; i++) {
var column = "<td>" + cats[i] + "</td>";
for (var j = 0; j < numberOfColumns; j++) {
column += "<td></td>";
}
$("#mytable").append("<tr>" + column + "</tr>");
}
现在按您描述的方式工作: https://jsfiddle.net/6Lzdejta/
答案 2 :(得分:0)
您可以使用嵌套循环来构建表。这是一个示例:
var cats = [ "a", "b", "c", "d", "e", "f"];
var dogs = [ "z", "y", "x", "w"];
var html = "";
for (var i = 0; i < cats.length; i++) {
html += "<tr>";
for (var j = 0; j < dogs.length; j++) {
html += "<td>";
html += "cats[" + i + "] = " + cats[i] + ", dogs[" + j + "] = " + dogs[j];
html += "</td>";
}
html += "</tr>";
}
document.getElementById("mytable").innerHTML = html;
<table id="mytable" border="1">
</table>
答案 3 :(得分:0)
您拼写错误的表格,并且表格中应该有一个正文。
let cats = ['persian', 'tabby', 'bengal'];
let dogs = ['shepard', 'terria'];
var numberOfRows = cats.length;
var numberOfColumns = dogs.length;
for (var i = 0; i < numberOfRows; i++){
var row = $("<tr>");
for (var j = 0; j < numberOfColumns; j++){
row.append($(`<td>`).text(`${cats[i]} - ${dogs[j]}`));
}
$("#mytable tbody").append(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "mytable">
<tbody>
<tr>
<td> Cats/dogs</td>
</tr>
</tbody>
</table>
答案 4 :(得分:0)
或使用Array.forEach
:
var cats = [ "a", "b", "c", "d", "e", "f"];
var dogs = [ "z", "y", "x", "w"]
var numberOfRows = cats.length;
var numberOfColumns = dogs.length;
cats.forEach(function (cat) {
$("#mytable").append(`<tr id="${cat}">`)
dogs.forEach(function (dog) {
$(`#${cat}`).append(`<td>${cat},${dog}</td>`)
})
})