为了账号安全,请及时绑定邮箱和手机立即绑定

遍历深度嵌套对象生成html optgroup/options

遍历深度嵌套对象生成html optgroup/options

不负相思意 2023-06-09 10:37:21
我正在尝试获取我的对象的键并创建一个 optgroup(如果它包含子项)然后创建 optgroup 的子项选项。如果一个孩子也是一个对象,那么我想在父 optgroup 中嵌套另一个 optgroup。下面是我的对象 myTypes我试图遍历它,然后使用适当的选项生成 html 选择,但我无法弄清楚。我得到的最远的是这个    let selectionHTML = "";    let paths = (arr)=>{        for(let i in arr){            if(typeof arr[i] == "object" && arr[i] !== null){                selectionHTML += "<optgroup label = '" + i + "'></optgroup>";                paths(arr[i]);            }        }    }    paths(myTypes);我不知道如何去生成我的代码。
查看完整描述

2 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

您需要知道使用嵌套optgroup元素的方法是行不通的,因为只会optgroup显示第一层:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup


尝试使用类似的东西:


const path = (source = {}) => {

  // Let the initial string be empty

  let returnedString = '';


  // Convert the object into an array using key/value pair and then iterate through it

  Object.entries(source)

    .forEach(([key, value]) => {

      if (typeof value === 'object' && value !== null) {

        // value is an object, iterate through it

        returnedString += `<optgroup label="${key}">${path(value)}</optgroup>`;

      } else {

        // value should be a string

        returnedString += `<option value="${key}">${value}</option>`;

      }

    });


  // Return the string

  return returnedString;

}


此外,在操作 DOM 时,建议使用内置方法来操作元素而不是字符串:


// Create the "root" element

// const root = document.createElement('select');


const path = (source = {}, rootElement = undefined) => {

  // Define the root element if not an instance of Element

  const root= rootElement instanceof Element ? rootElement : document.createElement('select');


  // Convert the object into an array using key/value pair and then iterate through it

  Object.entries(source)

    .forEach(([key, value]) => {

      if (typeof value === 'object' && value !== null) { // value is an object, iterate through it

        // Create an optgroup element

        const optgroup = document.createElement('optgroup');


        // Defines the attributes

        optgroup.setAttribute('label', key);


        // Add "content" inside the optgroup

        path(value, optgroup);


        // Append the newly created optgroup element to the root

        root.appendChild(optgroup);

      } else { // value should be a string

        // Create an option element

        const option = document.createElement('option');


        // Defines the attributes

        option.setAttribute('value', key);

        option.text = value;


        // Append the newly created option element to the root

        root.appendChild(option);

      }

    });


  // Return the root element

  return root;

}

编辑 1:在答案中添加了 DOM 方式


optgroup编辑 2:添加嵌套警告


查看完整回答
反对 回复 2023-06-09
?
Qyouu

TA贡献1786条经验 获得超11个赞

function getMyTypes(obj_myTypes) {


    var targetHTML = $("");

    

    for (const key in obj_myTypes) {

        if (obj_myTypes.hasOwnProperty(key)) {

            var element = obj_myTypes[key];

            console.log(key)

            targetHTML.prepend(`<optgroup id="one" label="${key}"> ${key} </optgroup>`);

            //each in obj

            //console.log(element)

            stepTwo(element)

        }

    }

}

getMyTypes(myTypes);


function stepOne() {

    var step_one = $('optgroup').filter('[id="one"]');

        step_one.each((index) => {

           // var result = $(this).text()

            step_one.prepend(`<optgroup id="two" label=""> two </optgroup>`)

        });

}

stepOne()


function stepTwo(obj_elem) {


    var step_two = $('optgroup').filter('[id="two"]');

    

    for (const key in obj_elem) {

        if (obj_elem.hasOwnProperty(key)) {

            var item_of_element = obj_elem[key];

            console.log('KEY: '+key)


            step_two.each((index,html_element) => {

                $(html_element).attr("label", value)

                console.log(value)

                //return value

            });

        }

    }

}


查看完整回答
反对 回复 2023-06-09
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信