我已经关注这个问题有一段时间了。 我想用 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
})
}
这是一个例子:
// The original object given by you
const givenAssets = {
1: ['Boat', 0, '10000'],
2: ['Carriage', 2, '30000']
};
// Get #all_asset
const assetContainer = document.querySelector('#all_asset');
// Define a class
class Asset {
// Set parameters
constructor(id, name, price, age) {
this.id = id;
this.name = name;
this.price = price;
this.age = age;
}
// Create HTML
addHtml() {
// 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 HTML element before the end of #all_asset
assetContainer.insertAdjacentHTML('beforeend', html);
}
}
// Make instances and put them into an array
let assets = [];
for (const key in givenAssets) {
assets.push(new Asset(key, givenAssets[key][0], givenAssets[key][1], givenAssets[key][2]))
}
// Execute .addHtml() on each asset one by one.
assets.forEach(asset => asset.addHtml());
index.html
[<div id="all_asset"/>][1]