你可以通过以下代码实现监听 tbody
下的所有 tr
,获取每行第一个 td
的值,并为点击行添加背景颜色:
展示详情
HTML
<table id="myTable">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody id="tableBody">
<tr>
<td>张三</td>
<td>25</td>
<td>男</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
<td>女</td>
</tr>
</tbody>
</table>
真实应用代码
<table class="table table-striped">
<thead>
<tr>
<th style="display: none">null</th>
<th>对接公司</th>
<th>联系人员</th>
<th>开始日期</th>
<th>结束日期</th>
<th>备注/手机</th>
</tr>
</thead>
<tbody id="tableBody">
{if $houseProject}
{foreach name="houseProject" id="item"}
<tr>
<td style="display: none">{$item['id']}</td>
<td>{$item['name']}</td>
<td>{$item['company_contact']}</td>
<td>{$item['starttime']}</td>
<td>{$item['endtime']}</td>
<td>{$item['remark']}</td>
<!-- <td>{$item['createtime']|date="Y-m-d H:i:s",###}</td>-->
</tr>
{/foreach}
{else /}
<tr>
<td colspan="5"></td>
</tr>
{/if}
</tbody>
</table>
<div>
<input id="c-companyAddBtn" type="button" value="新增">
<input id="c-companyEditBtn" type="button" value="修改">
<input id="c-companyDelBtn" type="button" value="删除">
<input id="c-id" type="hidden" value="{$row.id}">
</div>
JavaScript
var tableBody = document.getElementById('tableBody');
tableBody.addEventListener('click', function(event) {
var target = event.target;
if (target.tagName === 'TD') {
var row = target.parentNode;
var firstCell = row.cells[0];
var value = firstCell.innerText;
console.log('第一个单元格的值:', value);
// 清除其他行的背景颜色
var allRows = tableBody.getElementsByTagName('tr');
for (var i = 0; i < allRows.length; i++) {
allRows[i].style.backgroundColor = ''; // 清除背景颜色
}
// 为点击的行添加背景颜色
row.style.backgroundColor = 'lightblue';
}
});
编辑操作
//编辑项目人员
$("#c-companyEditBtn").on('click',function (){
if (selectedRowId == null) {
layer.msg('请点击编辑项', {icon: 2});
return false;
}
var house_id = $("#c-id").val();
Layer.open({
type: 2,
closeBtn: 1,
title: '项目人员',
content: "../../../../../xiluhouse/house/houseproject/edit?ids="+selectedRowId,
area: ['60%','80%'],
success: function(layero, index){
var body = layer.getChildFrame('body', index);
var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象,执行iframe页的方法:iframeWin.method();
},end: function(){
$.ajax({
type: 'POST',
url: 'xiluhouse/house/house/houseproject',
data: {house_id: house_id},
success: function (response) {
renderTable(response);
},
error: function (res) {
// 删除失败的处理逻辑
}
});
}
});
});
局部刷新表格数据
function renderTable(data) {
var tableHTML = "";
for (var i = 0; i < data.length; i++) {
tableHTML += "<tr>";
// 根据数据构建表格行
tableHTML += "<td style=\'display: none\'>" + data[i].id + "</td>";
tableHTML += "<td>" + data[i].name + "</td>";
tableHTML += "<td>" + data[i].company_contact + "</td>";
tableHTML += "<td>" + data[i].starttime + "</td>";
tableHTML += "<td>" + data[i].endtime + "</td>";
tableHTML += "<td>" + data[i].remark + "</td>";
// 添加更多列...
tableHTML += "</tr>";
}
// 将生成的HTML代码设置为表格的内容
document.getElementById("tableBody").innerHTML = tableHTML;
}