jQuery-获取表格单元格值

jQuery - Get table cell value

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

我有一个表,如下所示。价格通常来自数据库,这只是为了显示我的问题。

$(document).ready(function() {
    $(document).delegate('.amount input[type="text"]','keyup',(function() {
        var $this = $(this);
        var sub_total = $this.find('.sub_total');
        var price = $this.find('.price').text();
        var amount = $this.val();
        alert(price);
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
      <td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td>
      <td>Ticket:</td>
      <td class="price">20,50</td>
      <td class="sub_total"></td>
  </tr>
</table>

我想做的是:当用户在字段tickets中键入数字时,它应该更新字段sub_total。对于我拥有的jQuery,这是不起作用的。当我alert(price)时,我得到undefined。所以我想知道如何使sub_total字段具有自动更新的值。知道我在这一行下面还有更多这样的行可能也很有趣。因此,脚本一次只能更新一个特定行中的字段。

我已经尝试过但没有成功:如何使用jQuery获取表格单元格值;如何使用jQuery获取表格单元格值?;如何使用jquery 在表中的任何位置获取表单元格值

提前谢谢。

在查找.sub_title或.price元素之前,您需要遍历回父tr元素。

$(document).ready(function() {
    $(document).delegate('.amount input[type="text"]','keyup',(function() {
        var $this = $(this);
        var $tr = $this.closest("tr");
        var sub_total = $tr.find('.sub_total');
        var price = $tr.find('.price').text();
        var amount = $this.val();
        alert(price);
    }));
});

像这样更改代码

$(document).ready(function() {
    $(document).on('input[type="text"].amount', 'keyup', (function() {
        var $this = $(this);
        var sub_total = $this.closest("tr").find('.sub_total');
        var price = $this.closest("tr").find('.price').text();
        var amount = $this.val();
        alert(price);
    }));
});

find()将搜索孩子。因此,在使用find()之前,您应该先进入父tr

您可以使用closest("tr")来获取父tr元素

这是因为pricesub_total不是当前元素的子元素(因为find正在选择):

var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();

它们是容器CCD_ 14的父级或更简单的子级的兄弟姐妹。

尝试:

var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();

示例

<table id="#myTable">

我写这个:

function setCell( idTab, row, col, text) {
  var idCel = idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
  $(idCel).html(text);
}
function getCell( idTab, row, col ) {
  var idCel =idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
  return $(idCel).html();
}
setCell( "#myTab", 3, 4, "new value" );
alert( getCell("#myTab", 3, 4);