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生成代码,并且在元素没有被追加之后。
答案 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);
}