使用jquery创建容器数组

时间:2014-05-05 14:39:43

标签: javascript jquery css

模板:

<Div id='Container'>

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

</div>

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

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

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

        <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

2 个答案:

答案 0 :(得分:2)

试试这个:

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);
}

答案 1 :(得分:0)

上面的答案是纯粹的javascript,当然有效,但你问如何在jQuery中这样做,所以这里是一个jQuery版本,使用$ .each()方法迭代一个对象数组:

 var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
  $.each(mydata, function() {
    var template = '<div class="container">';
    template += '<div class="name">'+this.name+'</div>';
    template += '<div class="address">'+this.address+'</div>';
    template += '</div>';
    $('body').append(template);
  });

编辑: 如果您需要使用唯一ID编号的容器,也很容易:

var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
  $.each(mydata, function(index) {
    index=index+1; //so you start at 1 not 0
    var template = '<div id="container'+index+'">';
    template += '<div class="name">'+this.name+'</div>';
    template += '<div class="address">'+this.address+'</div>';
    template += '</div>';
    $('body').append(template);
  });