我想构建一个这样的页面,其中 B 列应该是可编辑的,每当用户更改 B 列中的值时,总计应该相应地重新计算。
我想构建一个这样的页面,其中 B 列应该是可编辑的,每当用户更改 B 列中的值时,总计应该相应地重新计算。
我想构建一个这样的页面,其中 B 列应该是可编辑的,每当用户更改 B 列中的值时,总计应该相应地重新计算。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
th {
}
</style>
</head>
<body>
<table id="myTable">
<col width="130">
<col width="80">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td>
<td class="someClass" contenteditable="true">400</td>
</tr>
<tr>
<td>Food</td>
<td class="someClass" contenteditable="true">200</td>
</tr>
<tr>
<td>Entertainment</td>
<td class="someClass" contenteditable="true">100</td>
</tr>
<tr>
<td>Transportation</td>
<td class="someClass" contenteditable="true">50</td>
</tr>
<tr>
<th>Total</th>
<td class="someTotalClass">200</td>
</tr>
</table>
<script>
function sumOfColumns(){
var totalQuantity = 0;
var totalPrice = 0;
$(".someClass").each(function(){
totalQuantity += parseInt($(this).html());
$(".someTotalClass").html(totalQuantity);
});
$(".classPrice").each(function(){
totalPrice += parseInt($(this).html());
$(".someTotalPrice").html(totalPrice);
});
}
sumOfColumns()
</script>
</body>
</html>
最佳答案
.blur()
将绑定(bind)一个处理程序以对 blur JavaScript 事件起作用——您只需将其添加到脚本标签中当前函数的下方就可以了。
通常我会说使用 .change()
但这似乎不适用于 contenteditable div。如果您可以更改为使用 <input>
而不是 <div contenteditable="true">
那么这可能是您的替代方案
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table,
td,
th {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
th {}
</style>
</head>
<body>
<table id="myTable">
<col width="130">
<col width="80">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td>
<td class="someClass" contenteditable="true">400</td>
</tr>
<tr>
<td>Food</td>
<td class="someClass" contenteditable="true">200</td>
</tr>
<tr>
<td>Entertainment</td>
<td class="someClass" contenteditable="true">100</td>
</tr>
<tr>
<td>Transportation</td>
<td class="someClass" contenteditable="true">50</td>
</tr>
<tr>
<th>Total</th>
<td class="someTotalClass">200</td>
</tr>
</table>
<script>
function sumOfColumns() {
var totalQuantity = 0;
var totalPrice = 0;
$(".someClass").each(function() {
totalQuantity += parseInt($(this).html());
$(".someTotalClass").html(totalQuantity);
});
$(".classPrice").each(function() {
totalPrice += parseInt($(this).html());
$(".someTotalPrice").html(totalPrice);
});
}
sumOfColumns();
$('.someClass').blur(function() {
sumOfColumns()
});
</script>
</body>
</html>
关于javascript - 每当用户更改(即编辑)html 表中列中的值时,总计将自动重新计算?我怎样才能实现它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021261/