Javascript 如何使用JQuery从表中选择最后一个非空单元格

Javascript 如何使用JQuery从表中选择最后一个非空单元格,javascript,jquery,null,html-table,tr,Javascript,Jquery,Null,Html Table,Tr,我有一个包含以下行和单元格的表: 指数 产品 描述 1. 苹果 果实 2. 香蕉 果实 3. 胡萝卜 蔬菜 我需要选择name='index'的最后一个td的值,该值不为null。任何人都知道如何做到这一点。使用以下选择器: $('td[name=index]:not(:empty):last') 出于纯粹的教育目的,这里有一个非jQuery版本: function getLastNonEmptyCell(tableSelector) { //Find parent table by se

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

指数 产品 描述 1. 苹果 果实 2. 香蕉 果实 3. 胡萝卜 蔬菜
我需要选择name='index'的最后一个td的值,该值不为null。任何人都知道如何做到这一点。

使用以下选择器:

$('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]
}

仅供参考,您的HTML无效。没有可用元素。很抱歉。拉比亚拉纳汗:你想要的td会一直在最后一个tr中吗?换句话说,如果第5行中的索引不是空的,但是第4行中的索引是空的,那么它应该给您第4行中的索引吗?很抱歉,我跳过了它,只是阅读了不使用jQuery的内容。我以后会更加注意:如果你误读了标题,我认为是ZeroBased_IX,我认为它不是null,使用jquery,如果使用这种方法,请小心空格。只有换行符的td将匹配:not:empty。很高兴看到非jQuery版本,但您没有尽可能地利用选择器引擎。为什么不document.queryselectoralltable 1 td:not:empty,然后只获取最后一个结果?这是一种更好的单行方法。干得好@squintThat不能开箱即用,因为它将返回所有不是空的td。必须做的事情:最后一个孩子返回最后一行。这就是我的意思,然后抓住最后一个结果。但我确实忘记了OP希望名称是索引,所以我应该键入table1td[name=index]:not:empty。最后一个孩子将导致此失败。因为OP没有说元素必须是其父元素的最后一个子元素,所以无论哪种方式,您都不希望它出现在那里