只有第一行适用于金额函数。

huangapple go评论93阅读模式
英文:

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*"

huangapple
  • 本文由 发表于 2023年8月10日 18:26:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定