首页 > 解决方案 > 无法获取表格单元格值

问题描述

我想通过单击按钮将一行数据添加到表的末尾。但是,我想在底部添加任何新行之前检查最后一个表格行是否有不完整的条目,这样我就不会提交空白行或无效数据。

因此,到目前为止,所有使用 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,并且不继续插入。

标签: htmldynamichtml-tablecell

解决方案


您可以使用 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';
}

推荐阅读