我正在开发一个简单的财务跟踪应用程序。在应用程序中,有一个包含所有支出账单的表格,然后是位于表格外部的总金额。
我正在尝试找到一种使用 JS 或 AJAX 的方法,以便当我选择表行中的 1 个复选框时,我可以在总计中包含/排除账单,并自动更新总计以反映排除/包含。
表行是动态创建的,因此每次添加新帐单时,行都会增加,这意味着复选框 ID 需要增加。
<div class="card-body">
  <table class="display table" style="width:100%" id="example">
    <thead class="table-heading">
      <tr class="table-border">
        <th scope="col">#</th>
        <th scope="col">CREDITOR</th>
        <th scope="col">DESCRIPTION</th>
        <th scope="col">CATEGORY</th>
        <th scope="col">AMOUNT</th>
        <th scope="col" style="text-align: center">INCLUDE / EXCLUDE</th>
      </tr>
    </thead>
    <tbody>
      {% for item in debts %}
      <tr class="table-border table-items">
        <td>{{ forloop.counter }}</td>
        <td>{{ item.creditor }}</td>
        <td>{{ item.description }}</td>
        <td>{{ item.category }}</td>
        <td>£{{ item.amount }}</td>
        <td><input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" class="table-checkbox" id="myCheckbox" /></td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
我有一点 JS
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})
当选中复选框时,这确实会触发警报,但这只会在第一个复选框上触发,因为这是具有相同 ID 的复选框。
所以这可能是一个棘手的任务,因为我需要复选框 JS 来知道选中复选框的行的金额是多少,然后从总数中减去该数字,反之亦然。也许这是错误的方法?
总数显示为:
<h3 class="text-right text-danger"><i class="mdi mdi-cube icon-size float-left"></i><span class="font-weight-bold">£{{total_monthly_outgoing|floatformat:2}}<span class="h6"> per month</span></span></h3>
谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你只需要委派
我必须在 h3 中展开你的 span,以免 JavaScript 变得非常混乱
给总数一个ID,这样比
document.querySelector("h3.text-danger span")更容易。此脚本不需要 ID
选中时包含
const totalContainer = document.querySelector("h3.text-danger span"); document.querySelector(".card-body").addEventListener("click", (e) => { if (!e.target.matches(".table-checkbox")) return; // not a checkbox const total = [...document.querySelectorAll(".table-checkbox:checked")] .map(chk => +chk.closest("td").previousElementSibling.textContent.slice(1)) // remove the pound .reduce((a,b)=> a+b); // sum totalContainer.textContent = `£${total.toFixed(2)}`; }).table-checkbox { border: 2px dotted #00f; display: block; background: #ff0000; }