0

我有两个数组var nodes = new Array("alpha","beta","omega"); var childnodes = new Array("one","two","three");。我想要的是从节点数组创建三个 div 元素,然后再向每个节点的数组 div 标签添加三个 div 元素,使其看起来像这样。

<div class="alpha">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>
<div class="beta">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>
<div class="omega">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>

如何在 jquery 中实现这一点?我当前的代码确实添加了父节点,但它没有将子节点添加到父节点。如何使以下代码工作?

这是我的代码

var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");

for (var i = 0; i < nodes.length; i++) {
    var parentNodes = "<div class='" + nodes[i] + "'></div>";
    console.log(parentNodes);
    for (var j = 0; j < childnodes.length; j++) {
        var childNodes  = "<div class='" + childnodes[j] + "'></div>";
        var p = $(parentNodes).attr('class');
        console.log($('.' + p).append(childNodes));
        $('.' + p).append(childNodes);
        console.log(childNodes);
    }
    $('body').append(parentNodes);
}

这是jsfiddle代码

4

2 回答 2

4
var nodes = ["alpha","beta","omega"];
var childnodes = ["one","two","three"];

$.each(nodes, function(i, node) {
    var div = $('<div>').addClass(node);
    $.each(childnodes, function(i, node) {
       $('<div>').addClass(node).appendTo(div);
    });
    div.appendTo('body');
})​

这是演示

于 2012-08-09T07:28:24.760 回答
1

迟到但另一个可能的例子:

var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");

    for (var i in nodes) {
        var $nodes = $('<div>'+nodes[i]+'</div>');
        for(var k in childnodes){
            var $child = $('<div>'+childnodes[k]+'</div>');
            $child.appendTo($nodes);
        }
        $nodes.appendTo('#container');           
    }
于 2012-08-09T07:33:22.030 回答