日期:2014-05-17 浏览次数:20754 次
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> function addPerson(){ //1创建<td>对象 var nameTd = document.createElement("td"); var nameInput = document.createElement("input"); nameInput.setAttribute("name", "name");// 给<input>标签的name属性赋值为name <input type='text' name='name'> nameTd.appendChild(nameInput); var birthTd = document.createElement("td"); var birthInput = document.createElement("input"); birthInput.setAttribute("name", "birth"); birthTd.appendChild(birthInput); var emailTd = document.createElement("td"); var emailInput = document.createElement("input"); emailInput.setAttribute("name", "email");// 给<input>标签的name属性赋值为email emailTd.appendChild(emailInput); //增加一个删除按钮(难点) var delTd = document.createElement("td"); var delInput = document.createElement("input"); delInput.value="delPsrson"; delInput.type="button"; /*两个注意点: * 1加入了onclick属性 * 2赋值时不能这样写:=delPerson(this),这表示传的是调用函数的值 */ delInput.onclick=function(){ delPerson(this); //表示调用delPerson()方法 }; delTd.appendChild(delInput); //32创建tr var tr = document.createElement("tr"); tr.appendChild(nameTd); tr.appendChild(birthTd); tr.appendChild(emailTd); tr.appendChild(delTd); //3添加tr var tb = document.getElementById("tb"); tb.appendChild(tr); } function delPerson(tag){ //注意不要写delete,是JS中的关键字 var tr = tag.parentNode.parentNode; var tb = document.getElementById("tb"); tb.removeChild(tr); } function getPerson(){ var name = document.getElementsByName("name"); var birth = document.getElementsByName("birth"); var email = document.getElementsByName("email"); for(var i=0;i<name.length;i++){ alert(name[i].value+" "+birth[i].value+" "+email[i].value); } } </script> </head> <body id="b"> <input type="button" value="add person" onclick="addPerson();"/> <input type="button" value="get person" onclick="getPerson();"/> <table border=2> <tbody id="tb">