【发布时间】:2018-03-22 20:39:34
【问题描述】:
我必须创建一个可以动态添加新行的表格。用户必须输入名字、姓氏、年龄等并选择组。根据用户的组选择,带有“朋友”的行应该具有特定的样式(例如绿色背景颜色),带有“家庭”粉红色背景颜色等。到目前为止,我已经添加了一个新行。
如何更改行样式?
function newTableRow() {
var newRow = document.createElement("tr");
var newFirst = document.createElement("td");
var newLast = document.createElement("td");
var newEmail = document.createElement("td");
var newAge = document.createElement("td");
var newDate = document.createElement("td");
var newGender = document.createElement("td");
var newGroup = document.createElement("td");
var table = document.getElementById("tab");
table.appendChild(newRow);
newRow.appendChild(newFirst);
newRow.appendChild(newLast);
newRow.appendChild(newEmail);
newRow.appendChild(newAge);
newRow.appendChild(newDate);
newRow.appendChild(newGender);
newRow.appendChild(newGroup);
newFirst.innerHTML = document.getElementById("first").value;
newLast.innerHTML = document.getElementById("last").value;
newEmail.innerHTML = document.getElementById("email").value;
newAge.innerHTML = document.getElementById("age").value;
newDate.innerHTML = document.getElementById("date").value;
newGroup.innerHTML = document.getElementById("group").value;
newGender.innerHTML = document.getElementById("gender").value;
if (document.getElementById("group").value == "family")
document.getElementById(newRow).className = "style1";
if (document.getElementById("group").value == "friend")
document.getElementById(newRow).className = "style2";
if (document.getElementById("group").value == "work")
document.getElementById(newRow).className = "style3";
}
#container {
text-align: center;
margin-left: auto;
margin-right: auto;
}
table,
th,
td {
border: solid black 1px;
border-collapse: collapse;
padding: 20px;
}
.style1 {
background-color: pink;
}
.style2 {
background-color: green;
}
.style3 {
background-color: blue;
}
<div id="container">
<div id="content">
<table id="tab">
<tr>
<th> First Name </th>
<th> Last name </th>
<th> Email </th>
<th> Age </th>
<th> Date of birth</th>
<th> Gender</th>
<th> Group</th>
</tr>
<tr id="row">
<td id="first1"><input type="text" id="first"></td>
<td id="last1"><input type="text" id="last"></td>
<td id="emal1"><input type="email" id="email"></td>
<td id="age1"><input type="number" id="age"></td>
<td id="date1"><input type="date" id="date"></td>
<td id="gender1">
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="male">Male<br>
</td>
<td id="group1">
<select id="group">
<option value="family">family</option>
<option value="friend">friend</option>
<option value="work">work</option>
</select>
</td>
</tr>
</table>
<button onclick="newTableRow()">Add</button>
</div>
</div>
【问题讨论】:
标签: javascript html css html-table