亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

遍歷深度嵌套對象生成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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號