gpt4 book ai didi

javascript - 使用 jquery 创建容器数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:29 25 4
gpt4 key购买 nike

模板:

<Div id='Container'>

<div id='name'></div>
<div id='address'></div>

</div>

然后我想通过使用 for 循环来使用此模板来复制它,每个容器中的名称和地址都不同。

我不想动态地重新创建整个模板,因为模板永远不会改变。

所以body上的输出应该是这样的:

        <Div id='Container'>

<div id='name'></div>
<div id='address'></div>

</div>

<Div id='Container1'>

<div id='name'></div>
<div id='address'></div>

</div>


<Div id='Container2'>

<div id='name'></div>
<div id='address'></div>

</div>

正文输出:

Container:

Tom
sample address

Container 1:

Richard.
address 2

Container 3:

John

address 3

最佳答案

试试这个:

for(var i = 0; i < 4; i++){
var container = document.createElement('div'),
name = document.createElement('div'),
address = document.createElement('div');
container.id = 'Container' + i;
name.className = 'name';
address.className = 'address';
container.appendChild(name);
container.appendChild(address);
document.body.appendChild(container);
}

//same thing using jQuery + people array for easy population
var people = [
{name: "Tom", address: "sample address"},
{name: "Richard", address: "address 2"},
{name: "John", address: "address 3"}
];

for(var i = 0, len = people.length; i < len; i++){
var container = $("<div id='Container" + i + "'><div class='name'>" + people[i].name + "</div><div class='address'>" + people[i].address + "</div></div>");
$('body').append(container);
}

关于javascript - 使用 jquery 创建容器数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475207/

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