简体   繁体   English

如何使用 JavaScript 创建多个具有动态数据的 select 框?

[英]How to create multiple select boxes with dynamic data using JavaScript?

I'm going to create a simple E-commerce application.我将创建一个简单的电子商务应用程序。 I have API call, which returns variations object like below.我有 API 调用,它返回变体 object 如下所示。 I want to dynamically generate variation boxes in this example my aim is to generate 2 select boxes, the first which holds all Color options and the second which holds all Value options.我想在此示例中动态生成变化框,我的目标是生成 2 个 select 框,第一个包含所有颜色选项,第二个包含所有值选项。 Right now I am receiving one option value, I want to receive options value like the现在我收到一个期权价值,我想收到像在此处输入图像描述 image which I have referred to.我提到的图像。 In addition, the select boxes are dynamic there can be more than three variations.此外,select 盒子是动态的,可以有超过三种变化。 How can I achieve this result?我怎样才能达到这个结果? Thanks in advance.提前致谢。

 var variations = [{ NameValueList: [ { Name: "Color", Value: ["Cloud White / Core Black"] }, { Name: "US Shoe Size (Women's)", Value: ["11"] }, ] }, { NameValueList: [ { Name: "Color", Value: ["Cloud White / Core Green"] }, { Name: "US Shoe Size (Women's)", Value: ["13"] }, ] }, { NameValueList: [ { Name: "Color", Value: ["Cloud White / Core White"] }, { Name: "US Shoe Size (Women's)", Value: ["15"] }, ] }, ] document.getElementById("generateVariations").addEventListener("click", () => { var html; variations.map(el => { html = el.NameValueList.map(nameValue => { return `<select name="${nameValue.Name}"> <option value="${nameValue.Value[0]}">${nameValue.Value[0]}</option> </select>` }) }) document.getElementById("variations2").innerHTML = html.join('') })
 <div id="variations2"></div> <button id="generateVariations">Generate variations</button>

I'm not sure but I think is what you want.我不确定,但我认为这是你想要的。

 var variations = [{ NameValueList: [{ Name: "Color", Value: ["Cloud White / Core Black"] }, { Name: "US Shoe Size (Women's)", Value: ["11"] }, ] }, { NameValueList: [{ Name: "Color", Value: ["Cloud White / Core Green"] }, { Name: "US Shoe Size (Women's)", Value: ["13"] }, ] }, { NameValueList: [{ Name: "Color", Value: ["Cloud White / Core White"] }, { Name: "US Shoe Size (Women's)", Value: ["15"] }, ] }, ] let colors = variations.map(v => v.NameValueList[0]); let sizes = variations.map(v => v.NameValueList[1]) document.getElementById("generateVariations").addEventListener("click", () => { var colors_select = `<select name="${colors[0].Name}"> ${colors.map(e=>{ return `<option value="${e.Value[0]}">${e.Value[0]}</option>` }).join()} </select>` var sizes_select = `<select name="${sizes[0].Name}"> ${sizes.map(e=>{ return `<option value="${e.Value[0]}">${e.Value[0]}</option>` }).join()} </select>` document.getElementById("variations2").innerHTML = colors_select + sizes_select; })
 <div id="variations2"></div> <button id="generateVariations">Generate variations</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM