简体   繁体   English

如何使用 JavaScript 生成动态 select 框?

[英]How to generate dynamic select boxes 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.我想动态生成变化框。 Right now I am receiving one option value, I want to receive options value like 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>

Thanks for answering my questions, this is the solution that I can propose.感谢您回答我的问题,这是我可以提出的解决方案。

First, we need to reconstruct the array of objects on variations using reduce() function, so we can loop easily on the next step.首先,我们需要使用reduce() function 重构variations对象数组,以便我们可以轻松地在下一步循环。 We can also use 1 loop for this but it will be messy, so I thought of we need to do it separately for at least it'll make less mess.我们也可以为此使用 1 个循环,但它会很混乱,所以我认为我们需要单独进行,至少这样会减少混乱。

So we want to reconstruct it to this:所以我们想把它重建成这样:

[
  "Color": ["Cloud White / Core Black", "Cloud White / Core Black", "Cloud White / Core Black"].
  "US Shoe Size (Women's)": ["11", "13", "15"]
]

Then now we can loop the newly reconstructed array of objects and convert it to a string using .join('') method, and render it on a div element.然后现在我们可以循环新重建的对象数组并使用.join('')方法将其转换为字符串,并将其呈现在div元素上。

 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", () => { // Reconstruct array of object to easier manage rendering of elements const new_variations = variations.reduce((a, b) => { // If property already exist in variable "a", push values, else, create one b.NameValueList.forEach(obj => { let found_variant // Finds an existing object based on the 'name' property and initialize it on the 'found_variant' variable if (found_variant = a.find(e => e.name === obj.Name)) { found_variant.options.push(obj.Value[0]); } else { a.push({ name: obj.Name, options: [obj.Value[0]] }); } }) return a }, []) // Loop using the new reconstructed array of objects to render const html = new_variations.map(obj => (` <label>${obj.name}</label> <select name="${obj.name}"> ${obj.options.map(option => `<option value="${option}">${option}</option>`).join('')} </select> `)).join('') document.getElementById("variations2").innerHTML = html })
 <div id="variations2"></div> <button id="generateVariations">Generate variations</button>

Sorry, but the structure for storing your data doesn't seem to be optimal.抱歉,存储数据的结构似乎不是最佳的。 But if it's given (you cannot change it), then that's that:)但是如果给定了(你不能改变它),那就是:)

 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"] }, ] }, ] const selectObjects = (variations) => { return variations.reduce((a, { NameValueList: c }) => { c.forEach(({ Name, Value }) => { if (typeof a[Name] === "undefined") a[Name] = [] a[Name] = [...a[Name], ...Value] }) return a }, {}) } const selectHtml = (name, values) => { let html = '' html += `<label>${name}<select id="${name}">` values.forEach(value => { html += `<option>${ value }</option>` }) html += '</select></label>' return html } const selectsHtml = (selectObjects) => { html = '' for (let key in selectObjects) { html += selectHtml(key, selectObjects[key]) } return html } const container = document.getElementById('container') container.innerHTML = selectsHtml(selectObjects(variations))
 <div id="container"> </div>

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

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