0

我正在从当前的 DOM 树中获取所有图像。我将它们显示到我的自定义统一 div 中并允许用户选择它们。

var allImgs = $('img');

allImgs.each(function (index) {
    var imgUrl = $(this).attr("src");
    var newImgTag = $('<img></img>');
    newImgTag.attr("src", imgUrl);
    newImgTag.attr("width", "100px");
    newImgTag.attr("height", "100px");

    $("#Image-Grid").append(newImgTag);  // this works

    newImgTag.click(function (event) {
        $('#Selected-Image').empty();
        $('#Selected-Image').append(newImgTag);   // this doesn`t work why????
    });
});

我能够让所有图像显示到我的统一 div 中。但是,当我从统一 div 中选择一张图片时。图像将无法正常显示。

例如,我随机选择一个时尚网站。 http://www.abercrombie.com/webapp/wcs/stores/servlet/ProductDisplay?catalogId=10901&storeId=10051&langId=-1&categoryId=12266&parentCategoryId=%5bLjava.lang.String%3b%403dc73dc7&topCategoryId=12203&productId=1014475

当我选择其中一张图片时,我注意到图片的 src 链接是这样的 /anf/50817/img/global/logo-print.png

为什么点击事件后面不能显示图片?

4

1 回答 1

1
newImgTag.click(function (event) {
        $('#Selected-Image').empty();
        $(this).clone().appendTo('#Selected-Image');
});

文件:


<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

(...) 正如 .append() 的讨论中所示,通常当一个元素被插入到 DOM 中的某个位置时,它会从其旧位置移动。所以,给定代码:

$('.hello').appendTo('.goodbye');

生成的 DOM 结构将是:

<div class="container">
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

为了防止这种情况,而是创建元素的副本,您可以编写以下内容:

$('.hello').clone().appendTo('.goodbye');

这将产生:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>
于 2012-09-09T09:05:47.580 回答