未用jQuery封装的方法,效果界面如下
代码如下
<!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">
<title>Insert title here</title>
<script type="text/javascript">
function delRow(){
var e = arguments[0] || window.event;
target = e.srcElement || e.target;
var tr = target.parentNode.parentNode;
var tb = document.getElementById("tbody1");
tb.removeChild(tr);
}
function enableBtn(){
var tb = document.getElementById("tbody1");
var btnAry = tb.getElementsByTagName("input");
for(var i=0; i<btnAry.length; i++){
if(btnAry[i].type=="button")
btnAry[i].disabled = "disabled";
}
var radioAry = tb.getElementsByTagName("input");
var radio = null;
/*
//不可以..在onchange触发时,radio并没有被checked..
for(var i=0; i<btnAry.length; i++){
if(btnAry[i].type="radio" && btnAry[i].checked=="checked"){
radio = btnAry[i];
break;
}
}
if(radio==null){
alert("xx");
return;
}
*/
var e = arguments[0] || window.event;
target = e.srcElement || e.target;
var tr = target.parentNode.parentNode;
var inputAry = tr.getElementsByTagName("input");
for(var i=0; i<inputAry.length; i++){
if(inputAry[i].type=="button"){
inputAry[i].removeAttribute("disabled");
}
}
}
function add(){
var nameVal = document.getElementById("name").value;
var ageVal = document.getElementById("age").value;
var reg = /^(\s)*$/g;
nameVal = nameVal.replace(reg,"");
if(nameVal==""||nameVal==null||ageVal==""||nameVal==null){
alert("请输入姓名和年龄");
return;
}
var tr1 = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var td4 = document.createElement("td");
//每行添加一个单选按钮
var rad = document.createElement("input");
rad.type = "radio";
rad.name = "r1";
//为单选按钮注册事件
rad.onchange = enableBtn;
//每行添加一个删除按钮
var btn1 = document.createElement("input");
btn1.type = "button";
btn1.value = "删除";
btn1.disabled = "disabled";
//为删除按钮注册事件
btn1.onclick = delRow;
td1.appendChild(rad);
td2.innerHTML = nameVal;
td3.innerHTML = ageVal;
td4.appendChild(btn1);
tr1.appendChild(td1);
tr1.appendChild(td2);
tr1.appendChild(td3);
tr1.appendChild(td4);
document.getElementById("tbody1").appendChild(tr1);
}
</script>
</head>
<body>
<form>
<table id="table1" border="1px red solid;" width="30%">
<tbody id="tbody1">
<tr>
<td>选择</td>
<td>姓名</td>
<td>年龄</td>
<td>操作</td>
</tr>
</tbody>
</table>
<br />
姓名<input type="text" id="name">
<br />
年龄<input type="text" id="age">
<br />
<input type="button" οnclick="add()" value="添加一条记录">
</form>
</body>
</html>
值得注意的是其中的这段代码
采用这段代码可以方便的获取到触发事件的对象(不同浏览器采用的方法不同,但如此可兼容)
var e = arguments[0] || window.event;//获取事件对象
target = e.srcElement || e.target;//获取触发事件的对象
//alert(target.tagName);//弹出触发事件对象的标签名