【问题标题】:After adding elements by JavaScript CSS hack don't work通过 JavaScript CSS hack 添加元素后不起作用
【发布时间】:2013-10-15 00:16:02
【问题描述】:

我使用 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 执行此操作时,hack 本身不起作用(应用了颜色样式,我看到了图片)。但是,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 代码并重新运行,您会看到我打算做什么。如果你取消注释,你会看到我失败了。

【问题讨论】:

  • 什么不起作用?你从来没有真正说过。
  • @cgatian 黑客。当我通过 JS 制作 DOM 时,div 是不合理的。
  • 请提供一个 jsfiddle。
  • @Oriol 完成,请查看帖子更新。

标签: javascript jquery html css dom


【解决方案1】:

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

$thumbnailsContainer.append(' ');

Demo

【讨论】:

  • 难以置信!你是我的救星。但是你能解释一下吗?对我来说,这看起来像是一种魔法。
  • 你需要空格,因为如果你的元素之间有任何东西,任何东西都可以将它们分开,并且你希望它们被分开。
猜你喜欢
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
相关资源
最近更新 更多