首页 > 解决方案 > Html select dropdownlist如何同时显示name和id

问题描述

我一直在寻找同样的问题但没有找到,我想要实现的是,我想在选项上同时显示 '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);
}
    }
  )
   })

标签: javascripthtmlloopsfor-loopfetch

解决方案


将 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);
}
    }
  )
   })


推荐阅读