我对下面代码的问题是,当我点击表格中的任何按钮(完全使用javascript生成)时,DivNumberString
值始终为5_5
。对此为何发生的任何见解?
<!DOCTYPE HTML>
<html>
<body>
<div id="TableForCountries" class="TableForCountries">
</div>
<script>
function AddTable() {
var TableDiv = document.getElementById("TableForCountries");
var Table = document.createElement("table");
Table.border = 1;
TableDiv.appendChild(Table);
var i, j;
var NumCountries = 5;
var NumSectors = 5;
for (i = 0; i < NumCountries; i++) {
var CurrentRow = Table.insertRow(i);
for (j = 0; j < NumSectors + 1; j++) {
var Cell = CurrentRow.insertCell(j);
var SectorString = String(i + 1) + "_" + String(j);
if (j == 0) {
var CountryData = document.createElement("div");
CountryData.id = SectorString;
var AddOrDelete = "add";
var CountryDataSelect = document.createElement("select");
var AddButton = document.createElement("button");
AddButton.onclick = function() {
AddOrDeleteDiv("add", SectorString);
};
CountryData.appendChild(CountryDataSelect);
CountryData.appendChild(AddButton);
Cell.appendChild(CountryData);
} else if (j == NumSectors) {
var CountryData = document.createElement("div");
var CountryDataSelect = document.createElement("select");
CountryData.id = SectorString;
var AddOrDelete = "add";
var DeleteButton = document.createElement("button");
DeleteButton.onclick = function() {
AddOrDeleteDiv("delete", SectorString);
};
CountryData.appendChild(CountryDataSelect);
CountryData.appendChild(DeleteButton);
Cell.appendChild(CountryData);
} else {
var CountryData = document.createElement("div");
var CountryDataSelect = document.createElement("select");
var AddButton = document.createElement("button");
AddButton.onclick = function() {
AddOrDeleteDiv("add", SectorString);
};
var DeleteButton = document.createElement("button");
DeleteButton.onclick = function() {
AddOrDeleteDiv("delete", SectorString);
};
CountryData.appendChild(CountryDataSelect);
CountryData.appendChild(AddButton);
CountryData.appendChild(DeleteButton);
Cell.appendChild(CountryData);
}
} //End of inner for
} //End of outer for
} //end of function
function AddOrDeleteDiv(AddOrDelete, DivNumberString) {
console.log(DivNumberString);
var CountryNumber = parseInt(DivNumberString.charAt(0));
var SectorNumber = parseInt(DivNumberString.charAt(2));
if (AddOrDelete == "add") {
document.getElementById(CountryNumber + "_" + String(SectorNumber + 1)).style.display = "inline";
} else {
document.getElementById(CountryNumber + "_" + SectorNumber).style.display = "none";
}
}
AddTable();
</script>
</body>
</html>
&#13;