如何获取表格单元格中的值

How to get the value within a table cell?

本文关键字:单元格 表格 何获取 获取      更新时间:2023-09-26

所以我有以下代码:

请查看JSFiddle:https://jsfiddle.net/gL2emr8h/3/

我想获取所选行的 ID 值。我不知道使用哪个函数从所选行中获取第一个单元格的值。目前,它正在被定义。

  <table class="table table-striped" style="min-width: 100%;">
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Type</th>
    </tr>
      <tr>
        <td>1</td>
        <td>Name1</td>
        <td>Type1</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Name2</td>
        <td>Type2</td>
      </tr>
    </table>

.CSS:

tr {
  background: #00eeff;
}
.active {
  background: #ff5500;
}

JavaScript:

 var selectedHazardId;
  $(function() {
    /* Get all rows from your 'table' but not the first one 
     * that includes headers. */
    var rows = $('tr').not(':first');
    /* Create 'click' event handler for rows */
    rows.on('click', function(e) {
        /* Get current row */
        var row = $(this);
        rows.removeClass('active');
        row.addClass('active');
        selectedHazardId = row.children('td')[0].html();
        console.log(selectedHazardId);
    });
});

通过索引从 JQuery 数组中提取项目(例如 $("*")[0] ) 将为您提供一个没有 $.html() 函数的 DOM 对象。若要使用此方法,您需要访问 textContent 属性:

selectedHazardId = row.children('td')[0].innerHTML;

要从 jQuery 数组中提取项目,同时将其保留为 JQuery 对象,您需要使用 $.eq()

selectedHazardId = row.children('td').eq(0).html();

或者,:eq()可以用作选择器:

selectedHazardId = row.children('td:eq(0)').html() ;

请将selectedHazardId = row.children('td')[0].html()更改为$(row.children('td')[0]).html()selectedHazardId = $(row.find('td')[0]).html()

问题是row.children('td')[0]是一个普通的 DOM 项,但.html是一个 jQuery 函数。

因此,如果您将 DOM 项包装在 jQuery 函数中,则可以使用 jQuery 的.html,或者您可以使用 DOM 项具有的本机属性之一。

j查询方式:

var idRow = row.children('td')[0];
selectedHazardId = $(idRow).html();

原生方式:

var idRow = row.children('td')[0];
selectedHazardId = idRow.innerText // or innerHTML or TextContent