英文:
Only first row works for amount function
问题
My sun
function works only for the first row's inputs. How to make it work independently for every row in the table?
我的 sun
函数仅适用于第一行的输入。如何使其独立地适用于表中的每一行?
英文:
My sun
function works only for the first row's inputs. How to make it work independently for every row in the table?
<script>
$(function() {
$("#num1, #num2, #num3",).on("keydown keyup", sum);
function sum() {
$("#sum").val(Number($("#num1").val()) * Number($("#num2").val()) );
$("#sum1").val(Number($("#sum").val()) - (Number($("#sum").val()) * (Number($("#num3").val()) / 100 )));
}
});
</script>
答案1
得分: 0
jQuery($ => { // DOM 就绪,$ 别名在范围内
function sum() {
const $row = $(this).closest("tr");
const $num1 = $row.find(".num1");
const $num2 = $row.find(".num2");
const $num3 = $row.find(".num3");
const $sum = $row.find(".sum");
const $sum1 = $row.find(".sum1");
$sum.val(Number($num1.val()) * Number($num2.val()));
$sum1.val(Number($sum.val()) - (Number($sum.val()) * Number($num3.val()) / 100));
}
$(".myTable").on("input", ".num1, .num2, .num3", sum);
});
英文:
Use classes (instead of unique IDs), and use references to the parent row like $row.find(".num1")
or $(".num1", $row)
:
jQuery($ => { // DOM ready and $ alias in scope
function sum() {
const $row = $(this).closest("tr");
const $num1 = $row.find(".num1");
const $num2 = $row.find(".num2");
const $num3 = $row.find(".num3");
const $sum = $row.find(".sum");
const $sum1 = $row.find(".sum1");
$sum.val(Number($num1.val()) * Number($num2.val()));
$sum1.val(Number($sum.val()) - (Number($sum.val()) * Number($num3.val()) / 100));
}
$(".myTable").on("input", ".num1, .num2, .num3", sum);
});
and use the "input"
event instead of "key*"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论