我是使用 javascript 的新手,我正在使用 Dom 元素并使用表格创建一个 crud 演示。
粗略代码:
<html>
<head>
<style type="text/css">
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>
<input type="text" id="name"><br /><br />
<input type="text" id="age"><br /><br />
<input type="text" id="email"><br /><br />
<input type="button" value="addNew" id="addNew"><br />
<div id="output"></div>
<script>
let rows = [{
name: "John",
age: 20,
email: "abc@gmail.com"
}, {
name: "Jack",
age: 50,
email: "pqr@gmail.com"
}, {
name: "Son",
age: 45,
email: "xyz@gmail.com"
}];
window.onload = building();
let addNew = document.getElementById("addNew");
addNew.onclick = function () {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let email = document.getElementById("email").value;
rows.push({
name,
age,
email
});
console.log(rows);
building();
}
function building() {
let html = "<h1>student-Info</h1><table align='center'>";
for (let i = 0; i < rows.length; i++) {
html += '<tr id="id' + i + '"data-row="' + i + '">';
html += "<td>" + rows[i].name + "</td>";
html += "<td>" + rows[i].age + "</td>";
html += "<td>" + rows[i].email + "</td>";
html += "<td><a href='#' data-action='delete'>DELETE</a></td>";
html += "<td><a href='#' data-action='edit'>Edit</a></td>";
html += '</tr>';
}
html += "</table>";
document.querySelector('#output').innerHTML = html;
let deleted = document.querySelectorAll('[data-action="delete"]');
for (let i = 0; i < deleted.length; i++) {
deleted[i].addEventListener('click', function () {
event.preventDefault();
let ival = this.closest('[data-row]').getAttribute('data-row');
let r = rows.splice(ival, 1);
building();
console.log(r);
})
}
let edited = document.querySelectorAll('[data-action="edit"]');
console.log(edited);
for (let i = 0; i < edited.length; i++) {
edited[i].addEventListener('click', function () {
event.preventDefault();
let row = this.closest('[data-row]');
let rid = row.getAttribute('data-row');
let td = row.firstElementChild;
let input = document.createElement("input");
input.type = "text";
input.value = td.innerText;
td.innerHTML = "";
td.appendChild(input);
input.onblur = function () {
td.removeChild(input);
td.innerHTML = input.value;
rows[rid] = input.value;
}
})
}
}
</script>
</html>
我在循环“表”中获取所有数组数据,但是当我单击编辑时,我无法转换“输入”字段中的所有“td”元素,只有第一个“”元素会被转换。
任何人有任何想法请帮助解决它。谢谢