用 JS(JavaScript )实现增删改查
学习内容:
需求
用 JavaScript 实现简单增删改查
实现代码
<!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>用户新增</title>
<script>
window.onload = () => {
// 给获取的 id 添加点击事件
// 添加用户
document.getElementById("btn_submit").onclick = function () {
let username = document.getElementById("username").value;
console.log(username);
let email = document.getElementById("email").value;
let tel = document.getElementById("tel").value;
let tbody = document.getElementById("userTbody");
if (username !== null && username !== '' && username !== undefined) {
// 设置要插入的表格行信息
let tr = "<tr id=\"" + new Date().getTime() + "\">\n" +
"\t\t\t\t<td>" + username + "</td>\n" +
"\t\t\t\t<td>" + email + "</td>\n" +
"\t\t\t\t<td>" + tel + "</td>\n" +
"\t\t\t\t<td><a href=\"javascript:delRow('" + new Date().getTime() + "')\">删除</a></td>\n" +
"\t\t\t</tr>";
// 把新插入的行信息插入表格中
console.log(tbody.innerText);
console.log(tbody.innerHTML);
tbody.innerHTML += tr;
} else {
alert("姓名不能为空!");
}
// 添加信息之后把表单设置为空
document.getElementById("username").value = "";
document.getElementById("email").value = "";
document.getElementById("tel").value = "";
};
document.getElementById("btn_removeAll").onclick = () => {
var tbody = document.getElementById("userTbody");
tbody.innerHTML = "";
};
};
// 删除用户
function delRow(id) {
let tr = document.getElementById(id);
tr.parentNode.removeChild(tr);
}
</script>
</head>
<body>
<form name="userForm">
<center>
用户录入<br/>
用户名:<input id="username" name="username" type="text" size=15/>
E-mail:<input id="email" name="email" type="text" size=15/>
电话:<input id="tel" name="tel" type="text" size=15/>
<input type="button" value="添加" id="btn_submit"/>
<input type="button" value="删除所有" id="btn_removeAll"/>
</center>
</form>
<hr/>
<table border="1" align="center" cellpadding=0 cellspacing=0 width=400>
<thead>
<tr>
<th>用户名</th>
<th>E-mail</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody id="userTbody">
<tr id="tr1">
<td>小肥羊</td>
<td>wujizhang@163.com</td>
<td>18212345678</td>
<td><a href="javascript:delRow('tr1')">删除</a></td>
</tr>
</tbody>
</table>
</body>
</html>
总结:
以上就是用 JS(JavaScript )实现增删改查的代码了,代码仅供参考,欢迎讨论交流。