gpt4 book ai didi

javascript - 计算最后一列单元格的值——涉及动态表行

转载 作者:行者123 更新时间:2023-11-29 22:31:22 25 4
gpt4 key购买 nike

考虑以下 HTML 表格:

<table id="myTable1">
<tr id="TR1">
<td><input type="text" id="quantity1" name="quantity1" /></td>
<td><input type="text" id="weight1" name="weight1" /></td>
<td><input type="text" id="sub_total1" name="sub_total1" /></td>
</tr>
</table>

我在这里要完成的是,我需要根据 中键入的值更新每一行sub_total 字段的值每次触发 keyup() 时,数量重量字段都在同一行

现在我相信,如果我正在处理的表只是静态的,这将是一项更易于管理的任务。但是包含动态添加表格行给我带来了麻烦。


用于动态添加行的 JQuery:

$(document).ready(function() {

var counter = 2;

$("#addButton").click(function() {

$('#myTable1 tr:last').after(
'<tr id="TR"><td><input type="text" name="quantity' + counter +
'" id="quantity' + counter + '" value=""></input></td>' +

'<td><input type="text" name="weight' + counter +
'" id="weight' + counter + '" value=""></input></td>' +

'<td><input type="text" name="sub_total' + counter +
'" id="sub_total' + counter + '" value=""></input></td></tr>'
);

counter++;
});
});

这里有用于计算小计的公式:

var sub_total  = ((170 * first 10 kilos) + (70 * the remaining weight)) * (quantity);

因此给定样本值:数量 = 10weight = 15,我们应该有

var sub_total  = ((170 * 10) + (70 * 5)) * (10);

我有以下内容作为开始,但“不太确定在这些函数中放置什么”

$('#myTable1 input[id^=\'quantity\'], #myTable1 input[id^=\'weight\']').live('keyup',function() {

$('#myTable1 input[id^=\'quantity\'], #myTable1 input[id^=\'weight\']').each(function(index, value) {
});
});

最佳答案

您可以使用 closest()以匹配修改元素的父表行。从那里,可以更轻松地找到 quantityweightsub_total 元素:

$("#myTable1 [id^=quantity], #myTable1 [id^=weight]").live("keyup", function() {
var $tr = $(this).closest("tr");
var quantity = parseInt($("[id^=quantity]", $tr).val());
var weight = parseInt($("[id^=weight]", $tr).val());

var firstTen;
if (weight <= 10) {
firstTen = weight;
weight = 0;
} else {
firstTen = 10;
weight -= 10;
}

$("[id^=sub_total]", $tr).val((170 * firstTen + 70 * weight) * quantity);
});

关于javascript - 计算最后一列单元格的值——涉及动态表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6773166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com