如何在 javascript 中显示下拉菜单

how to display dropdown in javascript

我正在尝试显示一个下拉列表 - 在下拉列表中我显示了一些处于选中状态的项目,其余项目应显示在 dropdwon 中。

下面是我的代码和数组,我需要在选中状态下显示

var arr1 = [ 
        {id: 2, name: "name2"},
        {id: 3, name: "name3"},
        {id: 4, name: "name4"},
        {id: 5, name: "name5"}
    ];

var arr2 = [
        {id: 2, name: "name2" },
        {id: 3, name: "name3" },
    ];


$('#DropDown').html('');
let html = '<select id="selected"  name="selected[]"  multiple>';
for (let x = 0; x < arr1.length; x++) {
  for (let j = 0; j < arr2.length; j++) {
    let selected = "";
    if (arr2[j].id === arr1[x].id) {
      selected = "selected";
    }
    html = html + ' <option  value="' + arr1[x].id + '"' + selected + '>' +
      arr1[x].name + '</option>';
  }
}
html = html + '</select>';
$('#DropDown').append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="DropDown"></div>

在输出中,我想显示下拉列表中的所有 arr1 项和处于选中状态的 arr2 元素。

问题是您在 arr2 的 for 循环中添加选项。

var arr1 = [ 
        {id: 2, name: "name2"},
        {id: 3, name: "name3"},
        {id: 4, name: "name4"},
        {id: 5, name: "name5"}
    ];

var arr2 = [
        {id: 2, name: "name2" },
        {id: 3, name: "name3" },
    ];


$('#DropDown').html('');
        let html = '<select id="selected"  name="selected[]"  multiple>';
        for (let x = 0; x < arr1.length; x++) {
            let selected = "";
            let arr1Id = arr1[x].id;
            let arr1Name = arr1[x].name;
            for (let j = 0; j < arr2.length; j++) {
               if (arr2[j].id === arr1[x].id) {
               selected = "selected";
             }
        }
        html = html + ' <option  value="' + arr1Id + '"' + selected + '>' +arr1Name + 
       '</option>';
    }
html = html + '</select>';
$('#DropDown').append(html);