javascript - 附加到 div 时,我的 jquery 被覆盖

标签 javascript jquery html clone

我在下面使用这个 HTML 片段,我想循环计数然后将每个图像 HTML 元素追加到一个 div 中,但是循环遍历下面的代码只有最后一个项目被追加。我认为它正在覆盖它或其他东西,或者元素的复制可能没有按照我的想法工作。

var $container = $('#facebook-body-container');
$container.empty();

var $albumImage = $(".facebook-image");

for (var i = 0; i < response.albums.data.length; i++) {
  var tempImage = $albumImage;
  $(tempImage).find(".thumbnail").attr("id", response.albums.data[i].id);
  $(tempImage).find("img").attr("src", response.albums.data[i].picture.data.url);
  $(tempImage).find(".album-title").text(response.albums.data[i].name);
  $(tempImage).find(".album-photo-count").text(response.albums.data[i].photo_count);
  $container.append(tempImage);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageThumbnailContainer" style="display: none;">
  <div class="col-sm-4 facebook-image">
    <div id="" class="thumbnail" style="border: 1px solid #ddd;">
      <img class="img-responsive" src="" />
      <div class="caption">
        <h4 class="album-title"></h4>
        <p class="album-photo-count"></p>
      </div>
    </div>
  </div>
</div>

最佳答案

在使用 clone() 更改属性之前,您需要先克隆元素 方法,否则 $albumImage 将引用相同的实例:

var tempImage = $albumImage.clone(true);

作为参数传递的 bool 值 true 指示事件处理程序和数据是否应与元素一起复制。

关于javascript - 附加到 div 时,我的 jquery 被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51704504/

相关文章:

html - 添加 unicode 字符后文本更改高度

javascript - 如何使用Jquery获取ID?

html - 使用 HTML+CSS 在输入上显示跨度

javascript - 在javascript中调用带有参数的函数时如何更改变量?

Javascript-将样式添加到数组中匹配的第一个值并丢弃其他值

javascript - FetchError : request to http://localhost:3000/api/projects failed, 原因 : connect ECONNREFUSED 127. 0.0.1 :3000 (Express/Next. Js)

javascript - Canvas 手电筒效果

javascript - JQuery 转义撇号和双撇号?

Wordpress 中的 jQuery CSS 冲突

javascript - 如何使用 Facebook Login 和 ReactJS 实现登录和注销?