【问题标题】:Cannot get table cell value无法获取表格单元格值
【发布时间】:2020-01-10 03:46:58
【问题描述】:

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

到目前为止,所有使用 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);
} .......

我想要实现的是,在我插入另一行之前,应检查最后一行的日期和位置列是否有有效条目。如果任一列为空或无效(我可以整理出每一列的验证方面),我将发出 return false,并且不继续插入。

【问题讨论】:

    标签: html dynamic html-table cell


    【解决方案1】:

    您可以尝试像这样获取输入的值。

    <script>
        $('#btnAddTimePlace').click(function () {
            var table = $("#tblTimePlaces")[0];
            var lastRow = table.rows[table.rows.length - 1];
            var inputs = $(lastRow).find("input").not("input[type=button]");
            for( i = 0; i < inputs.length; i++) {
                var v = $(inputs[i]).val(); // this is value of input
                alert(v);
            }
        });
    </script>
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多