You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Javascript全局变量counts未生效:作用域使用疑问求助

问题描述

我在add_to_download_entries()函数外部声明了全局变量counts,在$(document).ready()函数中调用它时,始终显示初始值1;但在add_to_download_entries()函数内测试时,counts会随选中的checkWills复选框数量变化,却无法在外部函数中同步该值。请问我是否错误使用了变量?

相关代码

HTML部分

<div class="modal-footer">
  <button class="btn btn-secondary boxShadow" data-dismiss="modal"><i class="fa-solid fa-circle-xmark"></i> Close</button>
  <button id="payment-sub-btn" class="btn btn-success float-right" style="background-color:#28a745!important" onclick="update_coupon();">Pay Now $</button>
  </form>
</div>
<td>
  <input type="checkbox" name="checkWills" onclick='add_to_download_entries("{{$will->id}}")' />&nbsp;
</td>

JS部分

var selected_lostwill_array = [];

var counts = 1;
var checkboxes;

function add_to_download_entries(data) {
  checkboxes = document.querySelectorAll('input[name="checkWills"]:checked');
  counts = checkboxes.length;
  if ($.inArray(data, selected_lostwill_array) >= 0) {
    selected_lostwill_array = $.grep(selected_lostwill_array, function(value) {
      return value != data;
    });
  } else {
    selected_lostwill_array.push(data);
  }
}
// DataTables Functions 
$(document).ready(function() {
  $('#org_lost_table').DataTable();
  $('#all_lost_table').DataTable();
  if (counts > 0) {
    let finalPrice = Number(counts) * Number(22);
    $("#payment-sub-btn").append(counts);
  } else $("#payment-sub-btn").append(0);
});
解决方案

你并没有错误使用全局变量,问题出在代码执行的时机上:

  • $(document).ready()里的代码只会在页面首次加载完成时执行一次,此时counts是初始值1,之后就算counts随复选框选中状态变化,这段代码也不会重新运行,所以按钮上显示的始终是初始值。
  • add_to_download_entries()里的counts确实在实时更新,但你没有在每次更新后同步更新按钮的显示内容。

修复步骤:

  1. 把更新按钮的逻辑抽成独立函数:
function updatePaymentButton() {
  // 先清空按钮原有的数字内容,避免重复追加
  $("#payment-sub-btn").text("Pay Now $");
  if (counts > 0) {
    let finalPrice = Number(counts) * Number(22);
    $("#payment-sub-btn").append(counts);
  } else {
    $("#payment-sub-btn").append(0);
  }
}
  1. 在$(document).ready()里调用这个函数完成初始化:
$(document).ready(function() {
  $('#org_lost_table').DataTable();
  $('#all_lost_table').DataTable();
  // 初始化按钮显示
  updatePaymentButton();
});
  1. 在add_to_download_entries()函数的最后调用这个函数,每次复选框状态变化时更新按钮:
function add_to_download_entries(data) {
  checkboxes = document.querySelectorAll('input[name="checkWills"]:checked');
  counts = checkboxes.length;
  if ($.inArray(data, selected_lostwill_array) >= 0) {
    selected_lostwill_array = $.grep(selected_lostwill_array, function(value) {
      return value != data;
    });
  } else {
    selected_lostwill_array.push(data);
  }
  // 更新按钮显示
  updatePaymentButton();
}

另外补充一点:你可以直接用selected_lostwill_array.length来代替counts变量,因为数组长度本身就和选中的复选框数量一致,这样能减少冗余变量,代码更简洁。

内容的提问来源于stack exchange,提问作者Hemlata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:37:31