【问题标题】:How to select the last cell from table which is not null, using JQuery如何使用 JQuery 从表中选择不为空的最后一个单元格
【发布时间】:2017-01-31 13:20:54
【问题描述】:

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

<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>

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

【问题讨论】:

  • 仅供参考,您的 HTML 无效。没有可用的 &lt;row&gt; 元素。
  • 很抱歉。我刚刚修好了。
  • @RabiaRanaKhan:你想要的td 会一直在最后一个tr 中吗?换句话说,如果row5 中的索引不是空的,但row4 中的索引是空的,它应该给你来自row4 的那个吗?

标签: javascript jquery null html-table tr


【解决方案1】:

使用以下选择器:

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

【讨论】:

  • 抱歉,我跳过了它,只是阅读了“不使用 jQuery”。以后会多注意的:)
  • 你误读了我认为 ZeroBased_IX 的标题,我认为它不为空,使用 jquery
  • 如果使用这种方法,请注意空格。只有换行符的td 将匹配:not(:empty)
【解决方案2】:

出于纯粹的教育目的,这里是一个非 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]
}

【讨论】:

  • 很高兴看到非 jQuery 版本,但您没有尽可能利用选择器引擎。为什么不document.querySelectorAll("#table1 td:not(:empty)"),然后直接抓取最后一个结果?
  • 这是一种更好的单行方法。干得好@squint
  • 这不是开箱即用的,因为这将返回所有不为空的td。必须做:last-child 返回最后一行。
  • 这就是我所说的“然后就抓取最后一个结果”。我确实忘记了 OP 希望 nameindex,所以我应该输入 "#table1 td[name=index]:not(:empty)":last-child 将导致此操作失败。由于 OP 没有说该元素必须是其父元素的最后一个子元素,因此无论哪种方式,您都不希望这样。
  • 好电话 :) @squint
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 2011-06-19
相关资源
最近更新 更多