【问题标题】:How do I loop through Javascript array objects with forEach to create an element?如何使用 forEach 循环遍历 Javascript 数组对象以创建元素?
【发布时间】:2019-07-06 20:28:42
【问题描述】:

我正在尝试使用 JavaScript forEach 循环遍历数组对象,然后该函数应创建一个 OPTION 元素,将其值设置为项目的 id,将其文本设置为项目的名称,然后将 OPTION 添加到 SELECT元素?

我尝试将每个项目作为模板文字返回

const currencies = [{
        id: 'USD', name: 'US Dollars'
      },     {    
        id: 'UGX', name: 'Ugandan Shillings'
      },     {
        id: 'KES', name: 'Kenyan Shillings'
      },     {
        id: 'GHS', name: 'Ghanian Cedi'
      },     {
        id: 'ZAR', name: 'South African Rand'
      }];

currencies.forEach(function(currency){    
  str = `<option value="${id}"></option>`   
})    

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    你可以这样做:

    const currencies = [{
      id: 'USD',
      name: 'US Dollars'
    }, {
      id: 'UGX',
      name: 'Ugandan Shillings'
    }, {
      id: 'KES',
      name: 'Kenyan Shillings'
    }, {
      id: 'GHS',
      name: 'Ghanian Cedi'
    }, {
      id: 'ZAR',
      name: 'South African Rand'
    }];
    
    const selectEl = document.querySelector('#selectEl');
    currencies.forEach(function(currency) {
      const option = document.createElement('option');
      option.setAttribute('value', currency.id);
      option.text = currency.name;
      selectEl.appendChild(option);
    })
    &lt;select id="selectEl"&gt;

    【讨论】:

      【解决方案2】:

      const currencies = [{ id: 'USD', name: 'US Dollars' }, { id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }];
      
      $('select').append(currencies.map(c => $(`<option value="${c.id}">${c.name}</option>`)));
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <select></select>

      【讨论】:

        【解决方案3】:

        您必须使用允许嵌入表达式的Template literals(用反引号 (` `) 括起来):

        const currencies = [{ id: 'USD', name: 'US Dollars' }, {
        id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }];
        var str = '';
        currencies.forEach(function(currency){
          str += `<option value=${currency.id}>${currency.name}</option>`;
        });
        
        document.getElementById('mySelect').innerHTML = str;
        &lt;select id="mySelect"&gt;&lt;/select&gt;

        【讨论】:

          【解决方案4】:

          这里有一种使用Array::map()Array::join() 的方法:

          const currencies = [
            {id: 'USD', name: 'US Dollars'},
            {id: 'UGX', name: 'Ugandan Shillings'},
            {id: 'KES', name: 'Kenyan Shillings'},
            {id: 'GHS', name: 'Ghanian Cedi'},
            {id: 'ZAR', name: 'South African Rand'}
          ];
          
          let sel = document.getElementById("mySelect");
          
          sel.innerHTML = currencies.map(
            ({id, name}) => `<option value=${id}>${name}</option>`
          ).join("");
          &lt;select id="mySelect"&gt;&lt;/select&gt;

          【讨论】:

            【解决方案5】:

            使用 jQuery

            const currencies = [{ id: 'USD', name: 'US Dollars' }, {
            id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }];
            
            currencies.forEach(function(currency){
              $('#list').append(`<option value="${currency.id}">${currency.name}</option>`)
            })
            <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            
            <select id="list"></select>

            纯JS

            const currencies = [{ id: 'USD', name: 'US Dollars' }, {
            id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }];
            
            currencies.forEach(function(currency){
              var el = document.getElementById('list');
              var elChild = document.createElement('option');
            
              // Give the new div some content
              elChild.innerHTML = currency.name;
              elChild.id = currency.id
            
              // Jug it into the parent element
              el.appendChild(elChild);
            })
            &lt;select id="list"&gt;&lt;/select&gt;

            【讨论】:

            • 没有 jQuery 怎么办?
            • 我添加了一个纯JS的sn-p。
            • 你需要设置值,而不是 id
            • 值由innerHTML设置
            猜你喜欢
            • 2018-07-17
            • 1970-01-01
            • 2022-01-09
            • 2019-12-16
            • 2021-03-24
            • 1970-01-01
            • 2015-10-15
            • 1970-01-01
            相关资源
            最近更新 更多