【问题标题】:Create the Dynamic dropdown in Javascript在 Javascript 中创建动态下拉菜单
【发布时间】:2022-01-06 21:52:54
【问题描述】:

有人指导我,如何在 javascript 中使用以下数组/JSON 创建动态下拉列表?

 [
    {
      "1": "001",
      "2": "002",
      "3": "003"
    }
];

我做了什么:

 let text = "<select class='form-control'><option value=''>All</option>";
                        
                        var array = [
                            {
                                "1": "001",
                                "2": "002",
                                "3": "003"
                            }
                        ];
                       
                        for (var i = 0; i < array.length; i++) {
                            // POPULATE SELECT ELEMENT WITH JSON.
                            text += '<option value=' + array[i]["1"] + '>'+ array[i]["1"] +'</option>';
                        }

【问题讨论】:

  • 向我们展示您的尝试。 SO 不是免费的代码编写服务。此处的目的是让您发布解决自己问题的尝试,并在其他人无法按预期工作时提供帮助。见How to Askminimal reproducible example
  • @charlietfl 先生,我已经尝试过了,但我无法实现。先生,我已经编辑了我的问题并粘贴了我所做的一切。

标签: javascript arrays json dropdown


【解决方案1】:

使用Object.entries() 读取对象中的字段。

var array = [
  {
    "1": "001",
    "2": "002",
    "3": "003"
  }
];
var x = document.createElement("SELECT");
x.setAttribute("id", "mySelect");
document.body.appendChild(x);

for (const [key, value] of Object.entries(array[0])) {
  var z = document.createElement("option");
  z.setAttribute("value", key);
  var t = document.createTextNode(value);
  z.appendChild(t);
  document.getElementById("mySelect").appendChild(z);
}       

【讨论】:

    【解决方案2】:

    使用 JavaScript 创建 Select 元素:

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the button to create a SELECT and an OPTION element.</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <script>
    const customItems = [
        {
          "1": "001",
          "2": "002",
          "3": "003"
        }
    ];
    
    function myFunction() {
      const x = document.createElement("SELECT");
      x.setAttribute("id", "mySelect");
      document.body.appendChild(x);
      
      for (let i = 0; i < customItems.length; i++) {
        for (let key in customItems[i]) {
            const z = document.createElement("option");
            z.setAttribute("value", customItems[i][key]);
            const t = document.createTextNode(customItems[i][key]);
            z.appendChild(t);
            document.getElementById("mySelect").appendChild(z);
        }
        
      }
    }
    </script>
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 2023-03-22
      • 2014-09-26
      • 2017-01-06
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多