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

如何动态更新HTML表格内全部下拉列表的最新分组选项值

问题根因

现有代码仅在创建下拉列表的瞬间读取一次<p id="myP">内的分组值,后续新增分组时,已经渲染完成的老列下拉不会自动同步新的分组数据,因此只有新增列的下拉能拿到最新值。

解决方案

新增全局更新下拉的逻辑,每次提交新分组后主动同步所有已存在的下拉选项,修改后的完整代码如下:

JavaScript代码

function createSelectEl(values) {
  var select = document.createElement("select");
  select.name = "group";
  // 保留默认选项
  const defaultOption = document.createElement("option");
  defaultOption.text = 'Select One';
  defaultOption.value = '';
  select.appendChild(defaultOption);
  for (const val of values) {
    if(!val) continue;
    var option = document.createElement("option");
    option.value = val;
    option.text = val;
    select.appendChild(option);
  }
  return select;
}

// 新增:统一更新所有已存在的下拉列表选项
function updateAllSelects() {
  // 拉取最新的全量分组值
  const baseValues = ["IT", "Cleaning", "Accountant"];
  const myP = document.querySelector('p#myP');
  const customGroups = myP.innerText.split(',').map(item => item.trim()).filter(item => !!item);
  const allGroups = [...baseValues, ...customGroups];

  // 遍历页面所有下拉列表同步更新
  document.querySelectorAll('select').forEach(select => {
    // 暂存用户已选择的值,更新后自动回填
    const selectedVal = select.value;
    // 清空原有选项,仅保留默认项
    select.innerHTML = '<option value="">Select One</option>';
    // 插入最新的分组选项
    allGroups.forEach(group => {
      const option = document.createElement("option");
      option.value = group;
      option.text = group;
      if(group === selectedVal) option.selected = true;
      select.appendChild(option);
    })
  })
}

let groupNum = 1;
const tableEl = document.getElementById('member_table');

// 新增表格列逻辑
function appendColumn() {
  for (let i = 0; i < tableEl.rows.length; i++) {
    const values = ["IT", "Cleaning", "Accountant"];
    const myP = document.querySelector('p#myP');
    var categories = myP.innerText.split(',').map(item => item.trim()).filter(item => !!item);
    values.push(...categories);
    createCell(tableEl.rows[i].insertCell(tableEl.rows[i].cells.length), createSelectEl(values), 'col');
  }
  tableEl.rows[0].querySelector('td:last-child').textContent = 'Group' + groupNum;
  groupNum++;
}

// 单元格创建逻辑
function createCell(cell, content, style) {
  var div = document.createElement('div');
  div.appendChild(content);
  div.setAttribute('class', style);
  div.setAttribute('className', style);
  cell.appendChild(div);
}

const submitBtn = document.querySelector('button.btn-primary');
const input = document.querySelector('input');
const myP = document.querySelector('p#myP');

submitBtn.addEventListener('click', function(e) {
  const inputValues = input.value.split(',').map(item => item.trim()).filter(item => !!item);
  if (inputValues.length === 0) return;
  if (myP.innerText == '') {
    myP.innerText = inputValues.join(',');
  } else {
    myP.innerText += ', ' + inputValues.join(',');
  }
  input.value = '';
  // 提交新分组后立即同步所有下拉选项
  updateAllSelects();
});

CSS代码

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

HTML代码

<h2>HTML Table</h2>
<table id="member_table">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

<h1>Existing Group</h1>
<p>IT, Cleaning, Accountant</p>
<h1>Add New Group</h1>
<p id="myP"></p>
<input type="tel" id="group" name="group" placeholder="enter group name">
<br><br>
<button type="button" class="btn btn-primary btn-sm">Submit</button>
<button onclick="appendColumn()">Add column</button>

内容的提问来源于stack exchange,提问作者WEI ZHUANG GOH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:54:00