使用jquery创建容器数组 [英] Creating an array of containers using jquery
本文介绍了使用jquery创建容器数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
模板:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
我想要使用这个模板,使用for循环来复制它的名称和地址每个容器都不同。
I want to then use this template by using a for loop to replicate it with the name and address within each container being different.
我不想动态重建整个模板,因为模板永远不会改变。
I don't want to recreate the whole template dynamically, as the template will never change.
因此,主体上的输出应该是这样:
So the output on the body should be like this:
<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);
}
这篇关于使用jquery创建容器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文