【发布时间】:2017-02-21 01:57:49
【问题描述】:
我正在处理一项任务,我需要使用 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";! -
确实如此。问题是 getEllyByTagName 返回一个集合(伪数组)你的按钮应该在第一个索引
document.getElementsByTagName("button")[0] -
@ibrahimmahrir 谢谢!
标签: javascript html dom