使用 for 和 forEach 循环从对象数组中填充 html ,,name“ div

Fill the html ,,name" divs from array of objects using for and forEach loop

提问人:Viktoria 提问时间:8/15/2023 更新时间:8/19/2023 访问量:27

问:

我已经为这个问题纠结了很长一段时间了。 我想从 js 对象数组中用 html 中的名称类填充 h2 元素。我尝试了 for 和 forEach 循环,但我得到的只是填充 html 元素(成功),但只有数组中的一个名称(最后一个)。

我看到我可以用数据集(data-id)属性来做到这一点,但我很好奇我是否可以只用循环来做到这一点。

谢谢你的帮助。

这是我的代码:

Html格式:

<div class="container">
      <section>
        <div class="notification">
          <h2 class="name" id="firstName"></h2>
          <p class="notif-text">reacted to your recent post My first tournament today!</p>
        </div>
      </section>
      <section>
        <div class="notification">
          <h2 class="name" id="secondName"></h2>
          <p class="notif-text">followed you</p>
        </div>
      </section>
      <section>
        <div class="notification">
          <h2 class="name"></h2>
          <p class="notif-text">has joined your group Chess Club</p>
        </div>
      </section>
</div>
const people = [

{fullName: 'Mark Webber', notifText: 'reacted to your recent post My first tournament today!', time: '1m ago', message: ''},

    {fullName: 'Angela Grey', notifText: 'followed you', time: '5m ago', message: ''},
    {fullName: 'Jacob Thompson', notifText: 'has joined your group Chess Club', time: '1 day ago', message: ''},

    {fullName: 'Rizky Hasanuddin', notifText: 'sent you a private message', time: '5 days ago', message: `Hello, thanks for setting up the Chess Club. I have been a member for a few weeks now and
    I am already having lots of fun and improving my game.`},
    {fullName: 'Kimberly Smith', notifText: 'commented on your picture', time: '1 week ago', message: ''},

    {fullName: 'Nathan Peterson', notifText: 'reacted to your recent post 5 end-game strategies to increase your win rate', time: '2 weeks ago', message: ''},

    {fullName: 'Anna Kim', notifText: 'left the group Chess Club', time: '2 weeks ago', message: ''}
]


 let names = document.querySelectorAll('.name')


 for(let i = 0; i < people.length; i++ ) {  

    names.forEach(function(oneName){
        oneName.textContent = people[i].fullName
    })
 }
loops for-loop foreach 数据集 填充

评论


答:

0赞 kaziveh 8/15/2023 #1

使用定义的对象列表在 div 中注入 HTML 组件的流程非常简单:all_asset

  1. 获取 div 元素。
  2. 使用对象数组创建 div 列表。
  3. 使用 forEach 循环将 div 对象插入到主 div 元素中。

以下是有关如何实现此目的的示例:

    // The original object given by you
    const givenAssets = {
      1: ['Boat', 0, '10000'],
      2: ['Carriage', 2, '30000']
    };
    
    // Get DOM Element with ID #all_asset
    const assetContainer = document.querySelector('#all_asset');
    
    // Define a class that will represent each object
    class Asset {
      // Set parameters
      constructor(id, name, price, age) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.age = age;
      }
    
      // Create HTML with your objects, using the array and Asset class
      addHtml() {
        // Variable HTML: Elements as string.
        let html = `
          <div class="touch_box col-sm-12" id="list_asset${this.id}">
            <br>
            <h4 id="asset_name${this.id}">${this.name}</h4>
            <p id="asset_price${this.id}">${this.price}</p>
            <hr>
            <p id="asset_age${this.id}">${this.age}</p>
            <hr>
          </div>`;
          
        // Add your objects inside #all_asset div using beforeend method
        assetContainer.insertAdjacentHTML('beforeend', html);
      }
    }
    
    // List of your Assets
    let assets = [];

    // For each object in your array, push them into our assets list
    for (const key in givenAssets) {
      assets.push(new Asset(key, givenAssets[key][0], givenAssets[key][1], givenAssets[key][2]))
    }
    
    // For each asset in assets[], addHtml() will add them inside #all_asset
    assets.forEach(asset => asset.addHtml());

索引:.html:

<div id="all_asset">
  <!-- The assets.forEach loop will add your objects inside this div. -->
</div>

推荐的文档阅读,以便更清晰地理解:

0赞 Viktoria 8/15/2023 #2

我尝试了不同的解决方案,它也奏效了。我错误地选择了使用 querySelector() 而不是整个容器的所有名称......然后在新 HTML 中返回它

let container = document.querySelector('.container')


window.addEventListener('DOMContentLoaded', function() {
    const showInHTML = people.map((person, index) => {
        return `<section>
        <div class="notification">
          <h2 class="name" id="firstName">${person.fullName}</h2>
          <p class="notif-text">reacted to your recent post My first tournament today!</p>
        </div>
        <div class="time">
          <p class="time-date">1m ago</p>
        </div>
        <div class="message">
          <p class="message-text"></p>
        </div>
      </section>`
    }).join('')

    container.innerHTML = showInHTML
})