javascript - 使用“getElementById”更改按钮背景
问题描述
我正在使用数据表来显示数据,并且在我的数据表的每个条目的对面都有一个按钮。
该按钮具有 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>
推荐阅读
- gatsby - 隐藏组件时如何处理导入
- java - 是否可以动态地将数据从数据库中提取到 java 中?
- sql - NetSuite 使用 CAST 和自定义字段保存搜索公式时出错
- awesome-wm - 有没有办法监控 awesome-wm 中可见客户列表的变化?
- javascript - 使用 FullCalendar 显示事件数组
- hl7-fhir - 在 XML 和 Json 之间转换 fhir
- sql - SQL - ROW_NUMBER 用于多条件 LEFT JOIN
- typescript - Typescript 接口继承和泛型类型推断
- vba - 基于登录信息的控制表单
- python - MSYS 上的 PyQtWebEngine