通过JavaScript添加元素之后,CSS hack无法正常工作

时间:2013-10-15 00:16:03

标签: javascript jquery html css dom

我使用hack来justify divs in the container(标记答案)。它在静态HTML中完美运行。

<div id="gallery-thumbnails">
    <div class="gallery-thumbnail">
        <img src="1.jpg" alt="alt" title="title">
    </div>
    <div class="gallery-thumbnail">
        <img src="2.jpg" alt="alt" title="title">
    </div>
    <div class="gallery-thumbnail">
        <img src="3.jpg" alt="alt" title="title">
    </div>
    <div class="gallery-thumbnail">
        <img src="4.jpg" alt="alt" title="title">
    </div>
    <span class="stretch"></span>
</div>

但是当我通过JS执行此操作时,黑客本身不起作用(应用颜色样式,我看到图片)。 Hovewer,diff工具说静态和生成的DOM版本是相同的。

这是代码

var thumbnailsContainer = $('#gallery-thumbnails');
$(thumbnailsContainer).children('*').each(function() {
    $(this).remove();
});

$(lists[index]).children('img').each(function(index, picture) {
    var thumbnail = $('<div>', { class: "gallery-thumbnail" });
    var thumbnailImage = $('<img>', { src: $(picture).attr('src'), alt: $(picture).attr('alt'), title: $(picture).attr('title') });
    $(thumbnail).append(thumbnailImage);
    $(thumbnailsContainer).append(thumbnail);
});

$(thumbnailsContainer).append($('<span>', { class: 'stretch'} ));

更新

JSFiddle is here。如果您评论JS代码并重新运行,您将看到我打算做什么。如果你取消注释,你会看到我失败了。

1 个答案:

答案 0 :(得分:1)

问题是你需要元素之间的空格,所以只需添加

$thumbnailsContainer.append(' ');

Demo