使用下拉值引用 JavaScript 对象时出现问题

Problems using dropdown values to reference a JavaScript object

我正在开发一个 table,它将根据在下拉菜单中选择的内容进行填充,但是当进行选择时,输出显示为未定义。 我正在尝试使用下拉值来引用函数内的对象。我想知道下拉列表中的值是否无法用于引用该函数,或者是否需要以某种方式更改该值才能在脚本中正常工作。

我是 Javascript 的新手,提前感谢您的任何建议。下面是我正在使用的代码示例。

function fillrow() {
  var selection = document.getElementById("description_dropdown").value;
  const fordmotorco = {
    sector: "Corporate Bonds",
    cusip: "ABC5132",
    coupon: "5%"
  };
  const abbvie = {
    sector: "Corporate Bonds",
    cusip: "A12345HJ",
    coupon: "3%"
  };

  document.getElementById("col0").innerHTML = selection.sector;
  document.getElementById("col1").innerHTML = selection.cusip;
  document.getElementById("col2").innerHTML = selection.coupon;
}
<table id="holdings">
  <thead>
    <th>Sector</th>
    <th>Cusip</th>
    <th>Coupon</th>
  </thead>
  <tr id=select_security_row>
    <td id="col0">-</td>
    <td id="col1">-</td>
    <td id="col2">-</td>
    <td id="col3">
      <select id="description_dropdown" type=text name=Cusip onchange="fillrow(this)">
        <option value="fordmotorco">Ford Motor Co</option>
        <option value="abbvie">Abbvie</option>
      </select>
    </td>
  </tr>
</table>

这是我的解决方案:

let data = {
  "fordmotorco": {
    sector: "Corporate Bonds",
    cusip: "ABC5132",
    coupon: "5%"
  },
  "abbvie": {
    sector: "Corporate Bonds",
    cusip: "A12345HJ",
    coupon: "3%"
  }
};

function fillrow(selectBox) {
  let selection = selectBox.value;
  document.getElementById("col0").innerHTML = data[selection].sector;
  document.getElementById("col1").innerHTML = data[selection].cusip;
  document.getElementById("col2").innerHTML = data[selection].coupon;
}
 <table id="holdings">
   <thead>
     <th>Sector</th>
     <th>Cusip</th>
     <th>Coupon</th>
   </thead>
   <tr id=select_security_row>
     <td id="col0">-</td>
     <td id="col1">-</td>
     <td id="col2">-</td>
     <td id="col3"><select id="description_dropdown" type=text name=Cusip onchange="fillrow(this)">
         <option value="fordmotorco">Ford Motor Co</option>
         <option value="abbvie">Abbvie</option>
       </select></td>
   </tr>
</table>   

选择时的值不会改变。更好的方法是将 change 事件侦听器附加到您的 <select>。请参阅文档 addEventListener, change 事件。所以每次在下拉列表中选择一个选项时,都会调用传入的回调函数addEventListener

这是对您的 JS 代码的建议更改:

function fillrow(value) {
  const data = {
    fordmotorco: {
      sector: 'Corporate Bonds',
      cusip: 'ABC5132',
      coupon: '5%',
    },
    abbvie: { sector: 'Corporate Bonds', cusip: 'A12345HJ', coupon: '3%' },
  }
  document.getElementById('col0').innerHTML = data[value].sector
  document.getElementById('col1').innerHTML = data[value].cusip
  document.getElementById('col2').innerHTML = data[value].coupon
}

document
  .getElementById('description_dropdown')
  .addEventListener('change', function (event) {
    fillrow(event.target.value)
  })


也附上了类似示例的工作 demo