我正在尝试根据该表的左侧单元填充html表。
因此,下面的代码创建了一个由变量填充的表:
<table id="myTable" ></table>
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8",
carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('myTable').find('td').each(function () {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
</script>
我也尝试在数组中循环但没有成功:
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8", carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
arr2.forEach(function() {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
}
</script>
我想要的是每个左侧单元格检查右侧单元格中是否具有相同的名称,并相应地打印carac。(N1应该在Name1旁边,依此类推)。
有什么想法吗? 谢谢你的帮助。
答案 0 :(得分:0)
你的代码有很多错误,例如在其范围之外使用arr2 / cell2,而不是使用#来获取id等。看看工作代码:
这有效:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<table id="myTable"></table>
<script>
var rightcell = [{
name: "Name2",
carac: "N2"
}, {
name: "Name8",
carac: "N8"
}, {
name: "Name5",
carac: "N5"
}];
var rightCellMap = {};
for (var index = 0; index < rightcell.length; index++) {
rightCellMap[rightcell[index].name] = rightcell[index].carac;
}
arr2 = [
"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10"
];
for (var j = 0; j < 10; j++) {
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('#myTable').find('tr').each(function (index, element) {
var firstTd = $(element).find('td:first')[0];
var firstTdData = firstTd.innerHTML;
if (firstTdData != '' && rightCellMap[firstTdData]) {
firstTd.nextSibling.innerHTML = rightCellMap[firstTdData];
} else {
firstTd.nextSibling.innerHTML = "nothing"
}
})
</script>