我使用数据表来显示数据,数据表的每个条目都有一个按钮。
该按钮具有onclick,它捕获一行中的参数并保存在数组中。
我想在选择某个条目时更改颜色,并在取消选择时重置。
以下是我正在做的事情,
function select(name){
var property = document.getElementByClassName('checkRule');
if( rArray.includes(name) ){
property.style.backgroundColor = "#FFFFFF"
const index = rArray.indexOf(name);
if (index > -1) {
rArray.splice(index, 1);
}
}else{
rArray.push(name);
property.style.backgroundColor = "#28a0ff"
}
console.log('ARRAY >> ', rArray);
}
HTML
<div class="col-12 table-design">
<div class="row panel panel-default c-panel">
<div class="panel-heading c-phead">EMPLOYEE LIST</div>
<div class="panel-body">
<table class="table table-striped" id="c_table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Employer</th>
<th scope="col">Checked/Unchecked</th>
</tr>
</thead>
<tbody>
<c:forEach items="${e_list}" varStatus="status" var="emp">
<tr>
<td>${status.index + 1}</td>
<td>${emp.getEmpName()}</td>
<td>${emp.getEmployer()}</td>
<td>
<button type="button" class="custom-control-input checkRule" id="checkRule" onclick="selectRule('${emp.getEmpName()}')"></button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
此代码只更改数据表的第一个元素的颜色。
我该怎么做?
我建议使用closest
和toggle
-更改背景色
function select(element) {
element.closest("tr").classList.toggle("colored-bg");
// Additional code to store in array if required
}
.colored-bg {
background-color: #28a0ff;
}
<div class="col-12 table-design">
<div class="row panel panel-default c-panel">
<div class="panel-heading c-phead">EMPLOYEE LIST</div>
<div class="panel-body">
<table class="table table-striped" id="c_table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Employer</th>
<th scope="col">Checked/Unchecked</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>name1</td>
<td>emp1</td>
<td>
<button type="button" class="custom-control-input checkRule" id="checkRule" onclick="select(this)">Click</button>
</td>
</tr>
<tr>
<td>2</td>
<td>name2</td>
<td>emp2</td>
<td>
<button type="button" class="custom-control-input checkRule" onclick="select(this)">Click</button>
</td>
</tr>
<tr>
<td>3</td>
<td>name3</td>
<td>emp3</td>
<td>
<button type="button" class="custom-control-input checkRule" onclick="select(this)">Click</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
请参阅下面的解决方案。
- 添加额外的id唯一密钥,请参阅下面的id参数
- 将onclick事件作为第二个参数传递额外的唯一密钥
- 在js函数中获取第二个参数,并将其添加到getElemetById中
function select(name,***Uid***){
var property = document.getElementById('checkRule'***+Uid***);
if( rArray.includes(name) ){
property.style.backgroundColor = "#FFFFFF"
const index = rArray.indexOf(name);
if (index > -1) {
rArray.splice(index, 1);
}
}else{
rArray.push(name);
property.style.backgroundColor = "#28a0ff"
}
console.log('ARRAY >> ', rArray);
}
<button type="button" class="custom-control-input checkRule" id="checkRule***${status.index + 1}***" onclick="selectRule('${emp.getEmpName()}','${status.index + 1}')"></button>