使用JS动态添加和减少指定行(简洁完整代码通过Firefox 测试)

本文介绍如何使用JavaScript动态地在HTML中添加和减少指定行,包括表单元素的创建、事件监听以及DOM操作的基本应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用JS动态添加和减少指定行
完整代码
以下代码经过Firefox 测试通过



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>

<body>
<table border="0" cellspacing="0" cellpadding="0">
<tbody id="tbody">
<tr>
<td><input type="text" name="text1" /></td>
<td><input type="text" name="text2" /></td>
<td><select name="select">
<option>item1</option>
<option>item2</option>
<option>item3</option>
<option>item4</option>
<option>item5</option>
</select></td>
<td><input type="button" value="Remove" onclick="removeRow(this.parentNode.parentNode)"></td>
</tr></tbody>
</table>
<input name="button" type="button" value="Add row" onclick="addRow()">
<script>
function addRow()
{
var root = document.getElementById("tbody");
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
root.appendChild(cRow);
}
function removeRow(r)
{
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr')
if(allRows.length>1)
root.removeChild(r);
else
alert("only one row left, you not need to remove it.");
}
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值