【问题标题】:How to generate dynamic select boxes using JavaScript?如何使用 JavaScript 生成动态选择框?
【发布时间】:2021-07-07 19:47:38
【问题描述】:

我将创建一个简单的电子商务应用程序。我有 API 调用,它返回如下所示的变体对象。我想动态生成变体框。现在我收到一个选项值,我想收到我提到的图像之类的选项值。此外,选择框是动态的——可以有三个以上的变化。我怎样才能达到这个结果?提前致谢。

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>

【问题讨论】:

  • 那么从您给出的给定代码示例中,在变量变量上,NameValueList 内的每个对象都应该有一个select 标记? Values 属性是否代表options 的数量?
  • 不,在这个例子中,我的目标是生成 2 个选择框,第一个包含所有颜色选项,第二个包含所有值选项
  • 因此,如果我们要实现您的示例,您会期望每个 select boxes 上都有 2 个 select boxes 和 3 个 options,它们的值都相同,对吧?
  • 是的,你是对的,值将是颜色(“云白色 / 核心黑色”,“云白色 / 核心绿色”,“云白色 / 核心白色”)和美国鞋码(“11” , "13", "15")

标签: javascript html css json api


【解决方案1】:

感谢您回答我的问题,这是我可以提出的解决方案。

首先,我们需要使用reduce() 函数重构variations 上的对象数组,这样我们就可以轻松地进行下一步循环。我们也可以为此使用 1 个循环,但它会很混乱,所以我认为我们需要单独执行它,至少它会减少混乱。

所以我们想把它重构成这样:

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

那么现在我们可以循环新重建的对象数组并使用.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>

【讨论】:

    【解决方案2】:

    抱歉,存储数据的结构似乎不是最佳的。但如果它是给定的(你不能改变它),那就是这样:)

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多