JS For-Loop 克隆次数过多

JS For-Loop Cloning Too Many Times

已编辑:(我确定了之前在评论中讨论的问题)

我的代码如下:

<script type="text/javascript">
        for(var i=0; i<5; i++){
            $(".image-wrap").clone().appendTo(".container").attr('id', ("reason" + i));
        }

</script>

出于某种原因,当我使用这种方法时,我得到了 div,class 为 "image-wrap",ID 为 "reason0",正如预期的那样,但随后有"image-wrap" 和 "reason1" 的两个实例,然后 "image-wrap" 和 "reason2," 的四个实例,依此类推。我的循环有什么问题?

there are two instances of "image-wrap" with "reason1" and then four instances of "image-wrap" with "reason2," and so on and so forth

是因为你使用了$(".image-wrap").clone()。实际上,该脚本针对 class "image-wrap."

的每个实例

因此,如果您只需要克隆 .image-wrap 的第一个实例,那么您可以使用 :first 伪选择器。请参阅下面的更新脚本..

$(".image-wrap:first").clone().appendTo(".container").attr('‌​id', ("reason" + i));

详细了解 :first 伪选择器 here