requirement:
- HTML tag only writes one line header
- Write dynamic tables through JS (automatically create as many rows of tables as there are groups of data)
- For learning and demonstration, fixed data is used, and background data is not involved
Code implementation:
HTML content:
full name
subject
achievement
operation
CSS content:
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
JS content:
//1. Prepare the data of students and store it in the form of array. Each array element is an object
var datas = [{
Name: 'Zhang San',
subject: 'JavaScript',
score: 100
}, {
Name: 'Li Si',
subject: 'JavaScript',
score: 98
}, {
Name: 'Wang Wu',
subject: 'JavaScript',
score: 99
}, {
Name: 'Zhao Liu',
subject: 'JavaScript',
score: 88
}, {
Name: 'ha ha',
subject: 'JavaScript',
score: 0
}];
//2. Create rows in tbody: we create a few rows for a few people (through the length of the array)
var tbody = document.querySelector('tbody');
for (var i = 0; i < datas.length ; I + +) {// the outer for loop tube line tr
//1. Create tr line
var tr = document.createElement('tr');
tbody.appendChild(tr);
//2. Create cells in a row (3 cells related to data) TD the number of cells depends on the number of attributes in each object
For (VaR K in data [i]) {// for loop string TD in
//Create cell
var td = document.createElement('td');
//Give TD the attribute value data [i] [k] in the object
// console.log(datas[i][k]);
td.innerHTML = datas[i][k];
tr.appendChild(td);
}
//3. Create a cell with 2 words to delete
var td = document.createElement('td');
td.innerHTML ='delete ';
tr.appendChild(td);
}
//4. Delete operation
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
//Click a to delete the row of current a (parent node of a parent node) node.removeChild (child)
tbody.removeChild(this.parentNode.parentNode)
}
}
// for(var k in obj) {
//K gets the property name
//Obj [k] is the property value
// }
Implementation effect:
clickdeleteButton, the corresponding line will be deleted.
Click to delete the data of “Zhang San”: