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

如何动态遍历对象数组为下拉框指定value和text字段实现代码复用

下拉框绑定函数改造方案

完全可以实现,只需调整原有函数增加两个动态指定字段的入参即可,同时可设置默认值兼容旧代码的调用逻辑,不需要修改原有业务代码。

改造后的函数代码

function bindDropDown(data, dropDown, defaultText, valueField = 'CategoryId', textField = 'CategoryName') {
   var items = "";
   items += `<option value="-1">Select ${defaultText}</option>`;
    $.each(data, function (i, item) {
      // 动态读取指定字段的值
      const optionValue = item[valueField];
      const optionText = item[textField];
      items += `<option value="${optionValue}">${optionText}</option>`;
    });
   $(dropDown).html(items);
 }

调用示例

  • 原有旧结构数据源调用(无需修改原有调用逻辑,完全兼容):
const categoryData = [
  {CategoryId: 1, CategoryName: 'Collision'},
  {CategoryId: 2, CategoryName: 'Groundig'}
];
bindDropDown(categoryData, '#categorySelect', '分类')
  • 新结构数据源调用,只需传入对应字段名即可:
const subCategoryData = [
  {SubCategoryId: 1, SubCategoryName: 'Collision'},
  {SubCategoryId: 2, SubCategoryName: 'Groundig'}
];
bindDropDown(subCategoryData, '#subCategorySelect', '子分类', 'SubCategoryId', 'SubCategoryName')

可选优化

如果需要兼容字段不存在的异常场景,可以加兜底逻辑避免显示undefined:

const optionValue = item[valueField] ?? '';
const optionText = item[textField] ?? '未命名';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:09:02