首页 > 解决方案 > 使用 JavaScript / jQuery 中数组中的选项递归填充选择字段

问题描述

我在 JavaScript 对象中有一些数据,需要递归地将其插入到选择字段中。问题是原始页面不是通过 AJAX 等加载,而是直接将整个数据加载到 DOM 中。因此,在页面加载之前,我们不知道会有多少子级别,因此需要递归算法

请考虑以下示例:

$(document).ready(function() {
  var jsonData = {
    "1": {
      "uid": 1,
      "value": "foo1",
      "label": "FOO1",
      "children": {
        "2": {
          "uid": 2,
          "value": "foo1a",
          "label": "FOO1a",
          "parent": 1
        },
        "3": {
          "uid": 3,
          "value": "foo1b",
          "label": "FOO1b",
          "parent": 1
        },
        "4": {
          "uid": 4,
          "value": "foo1c",
          "label": "FOO1c",
          "parent": 1
        }
      }
    },
    "5": {
      "uid": 5,
      "value": "foo2",
      "label": "FOO2",
      "children": {
        "6": {
          "uid": 6,
          "value": "foo2a",
          "label": "FOO2a",
          "parent": 5,
          "children": {
            "7": {
              "uid": 7,
              "value": "foo2a1a",
              "label": "FOO2a1a",
              "parent": 6,
              "children": {
                "8": {
                  "uid": 8,
                  "value": "foo2a1a1a",
                  "label": "FOO2a1a1a",
                  "parent": 7
                }
              }
            }
          }
        }
      }
    }
  };

  // works only for the 1st select field for now...
  // should fill the other fields with children options dependent on the selection in the 1st field
  $(jsonData).each(function() {
    $.each(jsonData, function(i) {
      $('#singleselect-subject-1').append(
        '<option value="' + jsonData[i].value + '" ' +
        '        data-uid="' + jsonData[i].uid + '">' + jsonData[i].label +
        '</option>'
      );
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-1"></select>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-2"></select>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-3"></select>

你有一个想法,如何使 JavaScript 中的这种递归起作用?jQuery3 存在于项目中,因此可以(并且实际上应该)在可能且有意义的地方使用。谢谢!

标签: javascriptjqueryhtmlrecursion

解决方案


推荐阅读