【问题标题】:Html select dropdownlist how to display name and id at the same timeHtml select dropdownlist如何同时显示name和id
【发布时间】:2020-04-05 19:53:39
【问题描述】:

我一直在寻找同样的问题,但没有找到,我想要实现的是,我想在选项上同时显示“nama”和“id”,所以当单击下拉列表时应该显示'wick dhdfyj97' 和 'abraham 15hndfj',这可能吗(在 javascript 中)?现在我已经设法只显示'nama'。这就是我的 json 的样子:

[{"nama ": "wick","id": "dhdfyj97",},{"nama ": "abraham","id": "15hndfj",}]

代码如下:

 .then(res =>{ 
    res.json().then(num => {
	
for (var o = 0; o < num.length; o++) {
    var i = document.getElementById("Select");
    var d = document.createElement("option");
    d.text = num[o].nama;
	
    i.add(d);
}
    }
  )
   })

【问题讨论】:

    标签: javascript html loops for-loop fetch


    【解决方案1】:

    我们可以使用字符串文字来添加两者。

     .then(res =>{ 
        res.json().then(num => {
           for (var o = 0; o < num.length; o++) {
                var i = document.getElementById("Select");
                var d = document.createElement("option");
                d.text = `${num[o].nama} ${num[o].id}`;
    
               i.add(d);
           }
        }
       )
     })
    

    我还建议只查询一次 html 标签并重复使用它,也可以直接使用 for of 循环遍历响应:

    const i = document.getElementById("Select");
    for (const item of num) {        
        const d = document.createElement("option");
        d.text = `${item.nama} ${item.id}`;
        i.add(d);
    }
    

    您可以在此处了解有关模板文字的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals 您可以参考 MDN 了解更多信息。

    【讨论】:

      【解决方案2】:

      将 nama 和 id 连接在一起:

       .then(res =>{ 
          res.json().then(num => {
      	
      for (var o = 0; o < num.length; o++) {
          var i = document.getElementById("Select");
          var d = document.createElement("option");
          d.text = num[o].nama + ' ' + num[o].id;
      	
          i.add(d);
      }
          }
        )
         })

      【讨论】:

        【解决方案3】:

        创建一个选项标记并将其textContent 分配给item.namaitem.id 的串联并将其附加到Select 标记, 您还看到"nama " 中的空格删除它,所以它应该是"nama",否则它将在option 标记中显示未定义

        let Array = [
            { "nama": "wick", id: "dhdfyj97" },
            { "nama": "abraham", id: "15hndfj" },
          ];
          let Select = document.getElementById("Select");
          Array.map((item) => {
            var d = document.createElement("option");
            d.textContent = item.nama + " " + item.id;
            Select.appendChild(d);
          });
        &lt;select id="Select"&gt; &lt;/select&gt;

        【讨论】:

          猜你喜欢
          • 2017-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-19
          • 2019-08-16
          • 2019-01-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多