使用对象数组中的两个值更新 HTML

Update HTML using two values from array of objects

我有一个对象数组,每个对象都有一个 agebalance 属性。

我有一个带有 self-select 字段的表单和一个循环遍历并使用所有 balances.age 值填充 self-select 的函数。

<form id="myForm">
  <select id="selectAge">
    <option>Age</option>
  </select>
</form>
var balances = [
    {
        age: 23,
        balance: 10000
    },
    {
        age: 25,
        balance: 24000
    }
]

function getAge(){    
  for(var i = 0; i < balances.length; i++) {
    var opt = balances[i].age;
    var el = document.createElement("option");
    el.text = opt;
    el.value = opt;
    select.add(el);
  }  
}

我想使用 selected age 值并将数组的相应余额插入下面的一些 HTML 中。

<h2>You should have $<span id="insertBalance"></span>.</h2> 

我对此一无所知,可能一开始就采取了错误的做法。如何找到每个 select 年龄的正确余额并将其显示在我的文档中?

你很接近。向下拉菜单添加事件侦听器以侦听更改。发生变化时,使用 findbalances 数组执行线性搜索以匹配 event.target.value,即所选年龄。

请注意,线性搜索很慢,因此如果搜索变成瓶颈,您可能希望将 balances 数组转换为对象或 Mapage->balance 对。

const balances = [
  {
    age: 23,
    balance: 10000
  },
  {
    age: 25,
    balance: 24000
  }
];

const selectEl = document.getElementById("select-age");
const balanceEl = document.getElementById("insert-balance");

for (const e of balances) {
  const opt = document.createElement("option");
  selectEl.appendChild(opt);
  opt.text = e.age;
  opt.value = e.age;
}

selectEl.addEventListener("change", event => {
  const found = balances.find(e => e.age == event.target.value);
  balanceEl.innerText = found ? found.balance : "";
});
<select id="select-age">
  <option>Age</option>
</select>
<h2>You should have $<span id="insert-balance"></span>.</h2>

const myForm    = document.getElementById('my-form')
  ,   balanceEl = document.getElementById("insert-balance")
  ,   balances  = [ { age: 23, balance: 10000 }, { age: 25, balance: 24000 } ] 
  ;
balances.forEach((elm,i)=>
  {
  myForm.selectAge.options[i] = new Option(elm.age, elm.balance)
  })
myForm.oninput=_=>  
  {
  balanceEl.textContent = myForm.selectAge.value
  }
myForm.onsubmit=e=> 
  {
  e.preventDefault()   // disable form submit
  }
balanceEl.textContent = myForm.selectAge.value
<form action="xxx" method="POST" id="my-form">
  <select name="selectAge">
    <optgroup label="Age">
  </select>
</form>

<h2>You should have $<span id="insert-balance"></span>.</h2>