1.41.用JS动态添加表格行,删除表格行
参考答案:
<html>
<head>
<title>Q041.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function addRow(){
var table = document.getElementById("table1");
var row = table.insertRow(table.rows.length);
var idCell = row.insertCell(0);
idCell.innerHTML = document.getElementById("txtID").value;
var nameCell = row.insertCell(1);
nameCell.innerHTML = document.getElementById("txtName").value;
var buttonCell = row.insertCell(2);
var button = document.createElement("input");
button.value = "删除";
button.onclick = function(){
delFunc(this);
};
buttonCell.appendChild(button);
}
function delFunc(btnObj){
var isDel = confirm("真的要删除吗?");
if(!isDel)
return;
var rowObj = btnObj.parentNode.parentNode;
var id = rowObj.getElementByTagName("td")[0].innerHTML;
var table = document.geElementById("table1");
for(var i = 1; i < table.rows.length; i++){
if(table.rows[i].cells[0].innerHTML == id){
table.deleteRow(i);
break;
}
}
alert("删除ID为" + id + "的数据.");
}
</script>
</head>
<body>
ID:
<input type="text" id="txtID"/>
Name:
<input type="text" id="txtName"/>
<input type="button" value="增加" onclick="addRow();"/>
<br/>
<br/>
<table id="table1">
<tr class="header">
<td>
产品ID
</td>
<td>
产品名称
</td>
<td></td>
</tr>
<tr>
<td>
1
</td>
<td>
book1
</td>
<td>
<input type="button" value="删除" onclick="delFunc(this);"/>
</td>
</tr>
</table>
</body>
</html>
参考答案:
<html>
<head>
<title>Q042</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function validate(){
var reg = new RegExp("^[0-9]+$");
var obj = document.getElementById("num");
if(!reg.test(obj.value)){
alert("请输入数字!");
}
}
</script>
</head>
<body>
<input type="text" name="num" id="num">
<input type="button" value="验证数字" onclick="validate()"/>
<br>
</body>
</html>