我有四个数组
arrayOne['orange','blue','green','red','yellow','purple','gray','tan','pink','violet']
arrayTwo['1001','1003','3453','78934','2389','3','8934']
arrayThree['TV','phone','laptop']
arrayFour['1','2','3','4','5','6','7','8','9','10']
我正在用html制作一个表格
<table class="table table-striped">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
我有一个脚本可以打开一个模式并附加到表中我试图让它为两列工作但它只用 ArrayOne 内容填充第一列
for (row = 0; row <$(this).data("arrayOne").length; row++ ){
$("#myModal").find(".table").append("<tr>
<td>"+$(this).data("arrayOne")[row]+"</td>");
for (j = 0; j <$(this).data("arrayTwo").length; j++ ){
$("#myModal").find(".table").append("<tr>
<td>"+$(this).data("arrayTwo")[j]+"</td></tr></tbody></table>");
}
}
上面的代码只会打印出
column1 column2 column 3 column 4
orange
blue
green
red
....
violet
最终结果应该是这样的
column1 column2 column 3 column 4
orange 1001 TV 1
blue 1003 phone 2
green 3453 laptop 3
red 78934 4
yellow 2389 5
等等
最佳答案
假设 arrayOne
具有所有必需的行,而在其他数组中这些行可能为空,您可以执行以下操作:
arrayOne.forEach(function(value, key){
let firstColumn = arrayOne[key],
secondColumn = arrayTwo[key]?arrayTwo[key]:"",
thirdColumn = arrayThree[key]?arrayThree[key]:"",
fourthColumn = arrayFour[key]?arrayFour[key]:"";
$("#myModal").find(".table").append('<tr><td>'+firstColumn+'</td><td>'+secondColumn+'</td><td>'+thirdColumn+'</td><td>'+fourthColumn+'</td></tr>');
});
关于javascript - 使用带有数据元素的 Javascript 附加到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439840/