我已经用DOM方法构建了一个表,输入了行和列的数量。现在,我需要按数组myBooks
的元素获取行数和列数,并将同一数组的值放入表中。我该怎么办?
<!DOCTYPE html>
<html>
<head>
<title>tabella dom</title>
<script type="text/javascript" src="tabellaDom.js"></script>
</head>
<body>
<form name="numeri">
Inserisci due valori: <br>
<input name="valore1">
<input name="valore2">
<br>
<input type="button" name="creaTabella" value="Crea Tabella" onclick="creaTable(numeri.valore1.value, numeri.valore2.value);">
<br>
<div id="myDynamicTable"></div>
</form>
</body>
</html>
function creaTable(a, b) {
var tableDiv = document.getElementById("myDynamicTable");
var tbl = document.createElement('table');
tbl.setAttribute("id", "tabella");
var tbdy = document.createElement('tbody');
tbl.appendChild(tbdy);
tbl.border = '1';
for (var j = 0; j < a; j++) {
const tr = document.createElement('tr');
console.log('tr.value');
tbdy.appendChild(tr);
const btnDelete = document.createElement('input');
btnDelete.setAttribute("type", "button");
btnDelete.setAttribute("value", "-");
tr.appendChild(btnDelete);
btnDelete.onclick = function() {
tr.remove();
};
for (var k = 0; k < b; k++) {
var td = document.createElement('td');
td.width = '75';
td.appendChild(document.createTextNode("Cella " + j + "," + k));
tr.appendChild(td);
}
}
tableDiv.appendChild(tbl);
}
var myBooks = [{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
答案 0 :(得分:0)
var data="";
b--;
if(b==0){
data=myBooks[a-1]['Book ID'];
}
else if(b==1){
data=myBooks[a-1]['Book Name'];
}
else if(b==2){
data=myBooks[a-1]['Category'];
}
else if(b==3){
data=myBooks[a-1]['Price'];
}
尝试此代码。这里a是行数,b是列数