You need to enable JavaScript to run this app. 如何在HTML中实现基于下拉框选择与jQuery表格总值的联动下拉菜单
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中实现基于下拉框选择与jQuery表格总值的联动下拉菜单

需求实现参考代码

以下示例基于 Google Workspace Directory API 开发,使用前需在Google Cloud控制台开通对应API、配置OAuth 2.0授权凭证,替换代码中对应参数即可运行。

1. HTML页面结构

<!-- 部门选择表单 -->
<div class="form-group">
  <label for="departmentSelect">请选择部门:</label>
  <select id="departmentSelect">
    <option value="sales">销售部</option>
    <option value="tech">技术部</option>
    <option value="finance">财务部</option>
  </select>
</div>

<!-- 金额统计表格 -->
<table id="amountTable" border="1" cellpadding="8">
  <thead>
    <tr>
      <th>费用项</th>
      <th>金额(英镑)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>办公用品采购</td>
      <td class="amount-col">89.5</td>
    </tr>
    <tr>
      <td>差旅费</td>
      <td class="amount-col">120</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>总金额</th>
      <th id="totalAmount">0</th>
    </tr>
  </tfoot>
</table>

<!-- 拉取到的人员列表展示区 -->
<div>
  <h3>匹配人员列表:</h3>
  <ul id="personList"></ul>
</div>

<!-- 引入jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

2. 核心逻辑代码(JS+jQuery)

// 替换为你自己的Google Cloud凭证
const GOOGLE_API_KEY = 'YOUR_API_KEY';
const GOOGLE_CLIENT_ID = 'YOUR_CLIENT_ID';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest';
const SCOPES = 'https://www.googleapis.com/auth/admin.directory.user.readonly';

// 计算表格总金额
function calculateTotal() {
  let total = 0;
  $('.amount-col').each(function() {
    total += parseFloat($(this).text()) || 0;
  });
  $('#totalAmount').text(total.toFixed(2));
  return total;
}

// 从Google拉取对应人员列表
async function getPersonList(department, isLowAmount) {
  $('#personList').empty();
  // 构造过滤条件:部门匹配+金额对应的人员角色
  let filter = `orgUnitPath=/departments/${department}`;
  filter += isLowAmount ? " AND isApprover=true" : " AND isManager=true";

  try {
    const response = await gapi.client.directory.users.list({
      'customer': 'my_customer',
      'maxResults': 10,
      'query': filter
    });
    const users = response.result.users;
    if (users && users.length > 0) {
      users.forEach(user => {
        $('#personList').append(`<li>${user.primaryEmail} (${user.name.fullName})</li>`);
      });
    } else {
      $('#personList').append('<li>未找到匹配人员</li>');
    }
  } catch (err) {
    console.error('拉取人员列表失败:', err);
    $('#personList').append('<li>拉取人员列表失败,请检查授权配置</li>');
  }
}

// 初始化Google API客户端
function initGapiClient() {
  gapi.client.init({
    apiKey: GOOGLE_API_KEY,
    clientId: GOOGLE_CLIENT_ID,
    discoveryDocs: [DISCOVERY_DOC],
    scope: SCOPES
  }).then(function() {
    // 监听部门选择变动
    $('#departmentSelect').on('change', function() {
      const selectedDept = $(this).val();
      const total = calculateTotal();
      const isLowAmount = total < 250;
      getPersonList(selectedDept, isLowAmount);
    });

    // 监听表格金额变动,自动重新计算和拉取人员
    $('#amountTable').on('DOMSubtreeModified', '.amount-col', function() {
      const selectedDept = $('#departmentSelect').val();
      const total = calculateTotal();
      const isLowAmount = total < 250;
      getPersonList(selectedDept, isLowAmount);
    });

    // 页面加载完成后默认触发一次
    calculateTotal();
    getPersonList($('#departmentSelect').val(), calculateTotal() < 250);
  }, function(error) {
    console.error('Google API初始化失败:', error);
  });
}

// 加载Google API客户端库
function loadGapi() {
  const script = document.createElement('script');
  script.src = 'https://apis.google.com/js/api.js';
  script.onload = function() {
    gapi.load('client:auth2', initGapiClient);
  };
  document.body.appendChild(script);
}

// 页面加载完成后启动
$(document).ready(function() {
  loadGapi();
});

注意事项

  • 授权配置:首次使用会弹出Google账号授权窗口,需要使用拥有人员目录读取权限的Workspace账号授权
  • 规则调整:当前逻辑为金额低于£250时拉取部门普通审批人,高于等于£250时拉取部门负责人,可自行调整getPersonList方法中的过滤规则匹配实际需求
  • 表格适配:如果你的表格结构和类名和示例不同,修改calculateTotal方法中的jQuery选择器即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 11:15:09