我的Javascript表遇到问题,并根据我创建的按钮删除了特定的行。我正在使用我在之前的任务中使用的一些逻辑来标记具有删除行的颜色的单元格。我不知道调用deleteRow函数的正确方法是使用onclick。这是我的代码:
var collection = [
{Header1:"1, 1" , Header2: "2, 1" , Header3:"3, 1", Header4: "4, 1"},
{Header1:"1, 2" , Header2: "2, 2", Header3:"3, 2", Header4: "4, 2" },
{Header1:"1, 3" , Header2: "2, 3" , Header3:"3, 3", Header4: "4, 3" }
];
function buildTable(array){
var newTable = document.createElement("table");
var properties = Object.keys(array[0]);
console.log(properties);
var firstRow = document.createElement("thead");
var newRow;
var newData;
var newHeader;
var button;
var deleteButton;
var editButton;
for(var i = 0; i < properties.length; i++)
{
newHeader = document.createElement("th");
newHeader.textContent = "Header" + " " + [i + 1];
firstRow.appendChild(newHeader);
}
newTable.appendChild(firstRow);
for(var j = 0; j < array.length; j++)
{
newRow = document.createElement("tr");
for(var k = 0; k < properties.length; k++)
{
newData = document.createElement("td");
var propName = properties[k];
newData.textContent = array[j][propName];
newRow.appendChild(newData);
}
deleteButton = document.createElement("BUTTON");
var deleteText = document.createTextNode("DELETE");
editButton = document.createElement("BUTTON");
var editText = document.createTextNode("EDIT");
deleteButton.appendChild(deleteText);
newRow.appendChild(deleteButton);
editButton.appendChild(editText);
newRow.appendChild(editButton);
newTable.appendChild(newRow);
}
return newTable;
}
var newTable = document.body.appendChild(buildTable(collection));
function deleteRow(tableID, currentRow){
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
if (row==currentRow.parentNode.parentNode) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
deleteButton.onclick = deleteRow(newTable, newRow);
当我点击删除按钮时没有任何反应。关于如何使用onclick命令正确调用deleteRow函数的任何建议?
答案 0 :(得分:0)
newRow
在您打电话时未定义
deleteButton.onclick = deleteRow(newTable, newRow);
它应该是
deleteButton.addEventListener('click', function(){ deleteRow(newTable, newRow); }, false);
答案 1 :(得分:0)
您的删除按钮超出范围,因此永远不会调用代码。尝试移动线
deleteButton.onclick = deleteRow(newTable, newRow);
在build循环中的buildTable函数内部。将console.write(“Hello”)添加到deleteRow函数的顶部以确保它被调用。