如何通过对象显示带有值和文本的选项标签 属性

How to display option tag with value and text, through an objects property

我正在尝试创建一个具有 attr 值的选项标签,并使用我的 startadd 对象中的地址作为其值,并且我正在尝试分配要为该选项显示的文本作为文本属性 来自 startadd 对象,但是当我输入代码时,我只在 console.log 上得到 (<option></option>) 我试图得到这样的东西:

<option value="aldama, los angeles, ca">Aldama</option>

这是我的代码:

var startadd = [
 {
   address: "ucla los angeles, ca ",
   text : "UCLA"
 }, 
 {
   address: "aldama elementary los angeles, ca ",
   text : "Aldama"
 },
 {
   address: "franklin high school los angeles, ca",
   text : "Franklin"
 },
];

//loop through topics array to display button in start
function createOptions() {
    //prevent duplicate 
    $("#start").empty();
    for (var i = 0; i <  startadd.length; i++) {
        //new element for option to be created
        var newOption = $('<option>');
        newOption.attr("value", startadd.address);
        newOption.text(startadd.text);
        $("#start").append(newOption);
    }
}
createOptions();

您需要为数组项编制索引。目前 startadd.address 不工作,因为 .address 不是数组的 属性。但是,它是数组中对象的 属性,因此您需要使用 startadd[i].addressstartadd[i].text

作为旁注,在循环中附加到 DOM 不是一个好主意,因为附加是一项昂贵的操作,相反,您可以考虑保留元素数组然后使用.html 将选项数组添加到 <select> 下拉列表中。

参见下面的示例:

var startadd = [{
    address: "ucla los angeles, ca ",
    text: "UCLA"
  },
  {
    address: "aldama elementary los angeles, ca ",
    text: "Aldama"
  },
  {
    address: "franklin high school los angeles, ca",
    text: "Franklin"
  },
];

function createOptions() {
  $("#start").empty();
  var newOptions = [];
  for (var i = 0; i < startadd.length; i++) {
    var newOption = $('<option>');
    newOption.attr("value", startadd[i].address); // add [i] here to index element
    newOption.text(startadd[i].text); // add [i] here to index element
    newOptions.push(newOption); // add new option to the array
  }
  $("#start").html(newOptions); // once loop is complete, add the array of elements to the DOM
}
createOptions();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="start"></select>

在这种情况下,你需要像那样指定 arr 的索引

newOption.attr("value", startadd[i].address);
newOption.text(startadd[i].text);

但我建议你应该使用 map() 函数或 each() 使它更容易

var startadd = [{address: "ucla los angeles, ca ",
 text : "UCLA"
 }, 
 {address: "aldama elementary los angeles, ca ",
 text : "Aldama"
 },
 {address: "franklin high school los angeles, ca",
 text : "Franklin"
 }];
    //loop through topics array to display button in start
    function createOptions() {
        //prevent duplicate 
        $("#start").empty();
         $(startadd).map((v)=>{
            let newOption = $('<option>');
            newOption.attr("value", v.address);
            newOption.text(v.text);
            $("#start").append(newOption);
         })

    }
    createOptions();