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);
//为行创建id单元格
var idCell = row.insertCell(0);
idCell.innerHTML = document.getElementById("txtID").value;
//为行创建name单元格
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;
//找到当前行的ID
var rowObj = btnObj.parentNode.parentNode;
var id = rowObj.getElementByTagName("td")[0].innerHTML;
//循环行,根据id定位需要删除的行,并删除
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
1.42.写出一个JavaScript表单验证,验证HTML表单中<input type="text" name="num" id="num">
输入项必须为数字
参考答案:
<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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20