gpt4 book ai didi

javascript - 在 JavaScript 中将多个 div 放入数组中

转载 作者:行者123 更新时间:2023-11-28 00:03:09 25 4
gpt4 key购买 nike

所以我的标记中有很多 div 看起来类似于:

<div class="container">
<div class="wrapper">
<h3>Title</h3>
<p>Some text</p>
</div>
</div>

标记看起来非常困惑,我对 JS 相当陌生,但想知道,是否可以将所有这些 div 放入一个数组中,然后使用 for 循环来迭代它们,然后打印它们。但仍然对每个 div 有足够的控制权,以便我可以更改它们的背景颜色?

到目前为止我的JS:

  var div = {
divInfo: [
{
title: "title",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing"
}
]
};

我目前只显示了一个 div,因为我仍在为 for 循环而苦苦挣扎。

有什么帮助/建议吗?谢谢!

最佳答案

你在寻找这样的东西吗?

$(document).ready(function() {
var arrayDivs = [
{
title: 'Title 1',
description: 'This is the description to Title 1',
backgroundColor: 'gray',
color: 'black'
},
{
title: 'Title 2',
description: 'This is the description to Title 2',
backgroundColor: 'blue',
color: 'red'
},
];

function init() {
for (var i = 0; i < arrayDivs.length; i++) {
var html = '';
html += '<div class="section" style="color:' + arrayDivs[i].color + '; background-color:' + arrayDivs[i].backgroundColor + ';">';
html += '<h3>' + arrayDivs[i].title + '</h3>';
html += '<p>' + arrayDivs[i].descritpion + '</p>';
html += '</div>';
$('.container').append(html);
}
};
init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="wrapper">
<h3>Title</h3>
<p>Some text</p>
</div>
</div>

关于javascript - 在 JavaScript 中将多个 div 放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com