【问题标题】:Update HTML using two values from array of objects使用对象数组中的两个值更新 HTML
【发布时间】:2020-04-20 18:10:50
【问题描述】:

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

我有一个带有自选字段的表单和一个函数,用于循环并使用所有 balances.age 值填充自选。

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

我想使用选定的年龄值并将数组的相应余额插入到下面的一些 HTML 中。

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

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

【问题讨论】:

    标签: javascript arrays innerhtml


    【解决方案1】:

    你已经很接近了。将事件侦听器添加到下拉菜单以侦听更改。发生更改时,使用findbalances 数组执行线性搜索,以匹配选定的年龄event.target.value

    请注意,线性搜索很慢,因此如果搜索变成瓶颈,您可能希望将 balances 数组转换为对象或将 Map 转换为 age-&gt;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>

    【讨论】:

    • 如此简单!谢谢参观。确认这对我有用。
    【解决方案2】:

    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>

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多