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

如何使用模板字面量动态设置select标签的选中选项?

优化方案:用数组遍历生成Option元素

你的代码可以通过将类型列表抽象为数组,结合map生成Option元素来简化,既避免重复代码,也不用维护selected数组和switch分支,具体实现如下:

/* 创建表格 */
let propertyTable = document.createElement('table');
propertyTable.classList.add('expand','ignore');

// 定义所有类型选项的数组,后续新增/修改类型只需调整这里
const types = ["number", "dropDown", "autoSet", "plotly", "gradeGroup", "generate"];

// 遍历数组生成所有option的HTML字符串
const optionsHtml = types.map(type => 
  `<option value="${type}" ${type === this.type ? 'selected' : ''} class="ignore">${type}</option>`
).join('');

/* 构建表格HTML */
propertyTable.innerHTML = `<tr class="ignore">
  <th class="ignore">ID</th>
  <td class="ignore"><input class="tile ignore" value="${this.id}"></td>
</tr>
<tr class="ignore">
  <th class="ignore">Type</th>
  <td class="ignore">
    <select class="tile ignore">
      ${optionsHtml}
    </select>
  </td>
</tr>`;

优化点说明:

  • 消除重复代码:不用手动编写每个<option>标签,所有选项统一维护在types数组中,新增类型只需往数组里加元素即可。
  • 简化选中逻辑:通过type === this.type直接判断是否添加selected属性,替代原来的switch分支和selected数组,逻辑更直观。
  • 修复原代码错误:修正了原代码中gradeGroup选项里的c${selected[4]} lass拼写错误。

这种写法既保持了模板字面量的简洁性,又让代码更易于维护,避免了手动编写重复DOM元素的繁琐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:47:31