动态表格
编辑器制作效果展示:
代码展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {transition: all 0.3s}
table {border: 5px solid deeppink;cursor: pointer;text-align: center;width: 100%;height: 300 pxpx;font-size: 30px}
th {border: 1px solid blue;color: hotpink}
th:hover {background-color: deepskyblue;color: white}
tr:hover {background-color: red;color: white}
td {border: 1px solid black}
td:hover {background-color: yellow;transform: scale(1.2);color: red}
td:active {transform: scale(0.9)}
.div {width: 100%;height: 100%}
.bt {width: 100%;height: 70px;background-color: yellow;outline: 0}
.bt:active {background-color: red}
</style>
</head>
<body>
<input type="text" id="input">
<hr>
<script>
// 传入数据
var data = [
{name: "栗子", money: "11$", id: "123", place: "海南", weidao: "苦", 选中状态: true},
{name: "李子", money: "22$", id: "124", place: "湖南", weidao: "辣", 选中状态: false},
// '{"name":"李子","money":"22$","id":"124","place":"湖南","weidao":"辣","选中状态":false}',
{name: "苹果", money: "33$", id: "125", place: "湖北", weidao: "酸", 选中状态: true},
{name: "香蕉", money: "44$", id: "126", place: "北京", weidao: "甜", 选中状态: true},
{name: "梨子", money: "55$", id: "127", place: "天津", weidao: "咸", 选中状态: true},
{name: "梨子", money: "55$", id: "127", place: "天津", weidao: "咸", 选中状态: false},
{name: "梨子", money: "55$", id: "127", place: "天津", weidao: "咸", 选中状态: true},
{name: "梨子", money: "55$", id: "127", place: "天津", weidao: "咸", 选中状态: true},
{name: "梨子", money: "55$", id: "127", place: "天津", weidao: "咸", 选中状态: true},
];
var oinput = document.querySelector("#input");
// 输入框数据转换 JSON文本 => 对象
oinput.addEventListener("blur", function () {
data.push(JSON.parse(oinput.value));
// console.log(JSON.parse(oinput.value));
console.log(data);
crt();
});
var ot = document.createElement("table");
// 添加表格
for (var i in data[0]) {
var oth = document.createElement("th");
oth.innerText = i;
ot.appendChild(oth);
}
crt();
// 表格的按钮操作
function crt() {
for (var i = 0; i < data.length; i++) {
var or = document.createElement("tr");
for (var j in data[i]) {
var od = document.createElement("td");
od.innerText = data[i][j];
or.appendChild(od);
if (j == "选中状态") {
od.innerText = "";
var oi = document.createElement("input");
oi.type = "checkbox";
oi.checked = data[i][j];
od.appendChild(oi);
}
}
ot.appendChild(or);
var obt = document.createElement("button");
var odiv = document.createElement("div");
obt.addEventListener("click", run);
function run(e) {
var e = e || event;
var oe = e.srcElement;
oe.parentNode.parentNode.parentNode.removeChild(oe.parentNode.parentNode);
data.pop();
}
odiv.className = "div";
obt.className = "bt";
obt.innerText = "删除";
odiv.appendChild(obt);
or.appendChild(odiv);
}
}
document.body.appendChild(ot);
// 有BUG,转载请调试
</script>
</body>
</html>
整理笔记时发现自己做的小demo,传上来了,么么哒!