我正在进行一项任务,需要使用Javascript创建表格。DOM使用Javascript单击按钮时删除表格行
我遇到了,我需要创建一个按钮和删除第一排我TBODY元素的问题。
我试过onclick
以及addEventListener
,他们都没有为我工作。
下面是我的代码
"use strict";
//Create table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";
//Create thead
var thead = document.createElement("thead");
table.appendChild(thead);
thead.insertRow(0);
for (var i = 0; i < 3; i++) {
thead.rows[0].insertCell(i);
}
thead.rows[0].cells[0].appendChild(document.createTextNode("Brand"));
thead.rows[0].cells[1].appendChild(document.createTextNode("Model"));
thead.rows[0].cells[2].appendChild(document.createTextNode("Price"));
//Create tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);
for (var i = 0; i < 2; i++) {
tbody.insertRow(i);
for (var j = 0; j < 3; j++) {
tbody.rows[i].insertCell(j);
}
}
tbody.rows[0].cells[0].appendChild(document.createTextNode("Honda"));
tbody.rows[0].cells[1].appendChild(document.createTextNode("Civic"));
tbody.rows[0].cells[2].appendChild(document.createTextNode("$17,460"));
tbody.rows[1].cells[0].appendChild(document.createTextNode("Ford"));
tbody.rows[1].cells[1].appendChild(document.createTextNode("Focus"));
tbody.rows[1].cells[2].appendChild(document.createTextNode("$25,540"));
var myButton = document.createElement("button");
document.getElementsByTagName("button").id = "newButton";
var text = document.createTextNode("Confirm to remove first row in tbody");
myButton.appendChild(text);
//Append them into body
document.body.appendChild(table);
document.body.appendChild(myButton);
我想这样的代码:
function removeFirstRow() {
var remove = document.getElementsByTagName("tbody");
remove.removeChild(remove.tbody.rows[0]);
}
document.getElementsByTagName("button").onclick=function() {
var clickIt = document.getElementsByTagName("button");
if (clickIt.addEventListener) {
clickIt.addEventListener("click", removeFirstRow, false);
} else if (clickIt.attachEvent) {
clickIt.attachEvent("onclick", removeFirstRow);
}
}
如何让我的按钮来删除第一行在TBODY当我点击它?
“我试过的onclick以及的addEventListener,他们没有为我工作。”没有在你的代码中看到这个.. –
对不起,我会编辑这个。 –
'document.getElementsByTagName(“button”).id =“newButton”;'将得到一个HTMLCollection,其按钮'myButton'不会被包含进来,只需使用'myButton.id =“newButton”;'! –