使用for循环通过javaScript添加的嵌套元素

时间:2016-12-27 07:03:49

标签: javascript html

JAVASCRIPT

var $tables = $('#generate-here');          
for (var i = 1; i <= 11; i++) {
    var $folder = $('#folder_'+i);
    $('<div />', { id: 'folder_'+i, class: 'grid_4'}).appendTo($tables);
    $('<a />', { href: 'images/full'+i+'.jpg', class: gal_item'}).appendTo($folder);
};

HTML

<div id="generate-here">
    <div class="grid_4">
        <a href="images/full3.jpg" class="gal_item">
            <img src="images/page2_img3.jpg" alt="">
            <div class="gal_caption">
                <time datetime="2014-01-01">01 Feb 16</time>
            </div>
            <span class="gal_magnify"></span>
        </a>
    </div>
</div>

我需要动态生成上面的html DOM结构,我尝试使用上面的代码但它只是为grid_4 div生成代码,并且在元素没有被追加之后。

2 个答案:

答案 0 :(得分:1)

由于您需要将生成的folder_分配给变量$folder,因此您尝试获取标识为folder_的已存在元素

var $tables = $('#generate-here'),
  $folder;
for (var i = 1; i <= 11; i++) {
  $folder = $('<div />', {
    id: 'folder_' + i,
    class: 'grid_4'
  }).appendTo($tables);
  $('<a />', {
    href: 'images/full' + i + '.jpg',
    class: 'gal_item'
  }).appendTo($folder);
};

答案 1 :(得分:0)

var $tables = $('#generate-here');          
for (var i = 1; i <= 11; i++) {

    $('<div />', { id: 'folder_'+i, class: 'grid_4'}).appendTo($tables);
    var $folder = $('#folder_'+i);
    $('<a />', { href: 'images/full'+i+'.jpg', class: 'gal_item'}).appendTo($folder);
}