这是我的实习办法,请大家指正~
window.onload = function() {
//为当前所有A标签绑定删除事件
remove();
//改变背景颜色
changeBgcolor();
document.getElementsByTagName("input")[0].onclick = function() {
addElement();
//这里很关键,为新增的元素绑定相关事件
remove();
changeBgcolor();
}
//增加元素
function addElement() {
var newtr = document.createElement("tr");
var td1 = document.createElement("td");
var main = document.getElementsByTagName("tbody")[0];
var lastTxt = first(last(main)).innerHTML;
var lastNum = lastTxt.substring(lastTxt.length - 1);
td1.innerHTML = "xh00" + (parseInt(lastNum) + 1);
var td2 = document.createElement("td");
td2.innerHTML = "杨小二";
var td3 = document.createElement("td");
var a = document.createElement("a");
a.innerHTML = "删除";
a.href = "javascript:;";
td3.appendChild(a);
newtr.appendChild(td1);
newtr.appendChild(td2);
newtr.appendChild(td3);
document.getElementsByTagName("tbody")[0].appendChild(newtr);
}
//计算最后一个元素节点
function last(father) {
var result = father.lastChild;
while (result && result.nodeType != 1) {
result = result.previousSibling;
}
return result;
}
//计算第一个元素节点
function first(father) {
var result = father.firstChild;
while (result && result.nodeType != 1) {
result = result.nextSibling;
}
return result;
}
//改变背景颜色
function changeBgcolor() {
var tr = document.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
tr[i].onmouseover = function() {
this.bgColor = "#f2f2f2";
}
tr[i].onmouseout = function() {
this.bgColor = "#FFF";
}
}
}
// 创建删除函数
function remove() {
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].onclick = function() {
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
}
}
}