jQuery-获取表格单元格值
jQuery - Get table cell value
我有一个表,如下所示。价格通常来自数据库,这只是为了显示我的问题。
$(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
元素
这是因为price
和sub_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);
相关文章:
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- 区分电子表格中的空单元格和0值
- 如何将jQuery/AAJAX结果放入表格单元格
- 在谷歌电子表格中循环单元格
- 使用下拉选择菜单高亮显示一行表格单元格
- 如何通过悬停或点击谷歌电子表格中的单元格来运行自定义功能
- 使用javascript下拉菜单更改表格单元格的颜色
- 表格单元格高度与背景高度匹配
- 在表格单元格中查找超链接
- 谷歌应用程序脚本-onFormSubmit-复制到电子表格中的单元格
- 为什么谷歌应用程序的电子表格setValue函数没有在单元格中设置值
- 数据表 ..如何根据表格的单元格值更改单元格的颜色
- 如何使用单击属性和工具提示动态创建表格单元格,该工具提示将超链接到页面
- 在 DIV 中定位表格单元格
- 单击时将表格单元格从范围更改为输入
- 使用 javascript 为 HTML 表格单元格指定颜色
- 将单击表格单元格重定向到其中的
- JQuery insertAfter();移动下一个表格单元格
- 将工作表复制到新的电子表格,将单元格值添加到新电子表格名称的末尾
- 单击并用CTRL+C复制值时高亮显示html表格单元格