html - 无法获取表格单元格值
问题描述
我想通过单击按钮将一行数据添加到表的末尾。但是,我想在底部添加任何新行之前检查最后一个表格行是否有不完整的条目,这样我就不会提交空白行或无效数据。
因此,到目前为止,所有使用 innerHtml、innerText 等获取给定单元格值的尝试都失败了。我什至尝试更改单元格的颜色以确认我指的是正确的单元格对象。我已经检查了这个论坛和其他网站,但无法找到如何获取单元格内容。
<table id="tblTimePlaces" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width:150px">Date</th>
<th style="width:150px">Location</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (TimesPlacesViewModel timeplace in Model.TimesPlaces)
{
<tr>
<td>@timeplace.IncidentDate</td>
<td>@timeplace.IncidentLocation</td>
<td><input type="button" value="Remove" onclick="RemoveTP(this)" /></td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td><input type="date" class="form-control" id="inDt"></td>
<td><input type="text" class="form-control" maxlength="25" id="inPl" /></td>
<td><input type="button" id="btnAddTimePlace" value="Add" /></td>
</tr>
</tfoot>
</table>
我的 btnAddTimePlace onClick 函数的开始......
$('#btnAddTimePlace').click(function () {
var table = $("#tblTimePlaces")[0];
var lastRow = table.rows[table.rows.length - 1];
for( i = 0; i < lastRow.cells.length -1; i++) {
cell = lastRow.cells[i];
cell.style.color='blue';
alert(cell.innerText);
} .......
我想要实现的是,在我插入另一行之前,应该检查最后一行的日期和位置列是否有有效条目。如果任一列为空或无效(我可以整理出每一列的验证方面),我将发出返回 false,并且不继续插入。
解决方案
您可以使用 Vanilla JavaScript(纯 JavaScript)轻松做到这一点,如下所示:
var table = document.getElementById('tblTimePlaces');
var lastRow = [].slice.call(table.rows).pop();
/* to get last row (converting HTMLCollection to array and getting last
element of array with pop() function )*/
for(var i=0; i < lastRow.children.length; i++) {
var textPut = lastRow.children[i].firstChild;
textPut.style.color='blue';
}
推荐阅读
- swift - SwiftUI - 使用 DatePicker GraphicalDatePickerStyle 作为只读日历
- java - 如何在多线程中并行启动 Java 线程?
- php - 如何将简单的php数组转换为带头的json数据
- javascript - 编写 JS 存储 10 个值但 TypeError: input is a void element tag and must not have `children` 也不能使用 `dangerouslySetInnerHTML
- java - 无法使用java在android上发送每日通知
- javascript - 在内容脚本中打开弹出窗口(chrome 扩展)
- php - 使用可调用添加到 Laravel 查询
- next.js - 如何仅在 nextjs 应用程序的一页上隐藏标题?
- java - 如何同时将数据从一个活动传递到两个或多个活动?
- c# - 在多线程问题中没有得到预期的输出