How to add Drop-Down list (<select>) programmatically?

前端 未结 9 2213
北恋
北恋 2020-11-27 14:12

I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<         


        
9条回答
  •  借酒劲吻你
    2020-11-27 14:18

    const countryResolver = (data = [{}]) => {
        const countrySelecter = document.createElement('select');
        countrySelecter.className = `custom-select`;
        countrySelecter.id = `countrySelect`;
        countrySelecter.setAttribute("aria-label", "Example select with button addon");
    
        let opt = document.createElement("option");
        opt.text = "Select language";
        opt.disabled = true;
        countrySelecter.add(opt, null);
        let i = 0;
        for (let item of data) {
            let opt = document.createElement("option");
            opt.value = item.Id;
            opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
            countrySelecter.add(opt, null);
        }
        return countrySelecter;
    };
    

提交回复
热议问题