如何 select 来自 table 的最后一个不为空的单元格,使用 JQuery

How to select the last cell from table which is not null, using JQuery

我有一个 table 包含以下行和单元格:

<table id='table1'>
  <tr id='row1'>
    <th>index</th>
    <th>Product</th>
    <th>Description</th>
  </tr>
  <tr id='row2' name='row'>
    <td name='index'>1</td>
    <td name='product'>Apples</td>
    <td name='description'>fruits</td>
  </tr>
  <tr id='row3' name='row'>
    <td name='index'>2</td>
    <td name='product'>Bananas</td>
    <td name='description'>fruits</td>
  </tr>
  <tr id='row4' name='row'>
    <td name='index'>3</td>
    <td name='product'>Carrots</td>
    <td name='description'>vegetables</td>
  </tr>
  <tr id='row5' name='row'>
    <td name='index'></td>
    <td name='product'></td>
    <td name='description'></td>
  </tr>
</table>

我需要 select name='index' 的最后一个 td 的值,它不为空。任何人都知道如何做到这一点。

使用以下选择器:

$('td[name=index]:not(:empty):last')

出于纯粹的教育目的,这里有一个非 jQuery 版本:

function getLastNonEmptyCell(tableSelector) {
  //Find parent table by selector
  var table = document.querySelector(tableSelector)
  //Return null if we can't find the table
  if(!table){
    return null;
  }
  var cells = table.querySelectorAll("td")
  var lastNonEmptyCell = null;
  //Iterate each cell in the table
  //We can just overwrite lastNonEmptyCell since it's a synchronous operation and the return value will be the lowest item in the DOM
  cells.forEach(function(cell) {
    //!! is used so it's so if it is not null, undefined, "", 0, false
    //This could be changed so it's just cell.innerText.trim() !== ""
    if (!!cell.innerText) {
      lastNonEmptyCell = cell;
    }
  })

  return lastNonEmptyCell;
}

var cell = getLastNonEmptyCell("#table1")

编辑

正如@squint 所建议的那样,这可以更简洁地完成:

function lastNonEmptyCell(tableSelector) {
  //Since we want the last cell that has content, we get the last-child where it's not empty. This returns the last row.
  var row = document.querySelectorAll(tableSelector + " td:not(:empty):last-child")
  //Just grabbing the last cell using the index
  return row[row.length - 1]
}