使用jQuery将img元素复制到另一个div中

3

我有一个简单的带有单个图像的div。我想将同样的img元素复制到另一个div中。

$('.copy').click(function() {
    imageElement = $(this).siblings('img.source')[0];

    item = $('<div class="item">' + imageElement + '</div>');
});

我得到了这个:
[object HTMLImageElement]

代替实际的图像标签呈现。有什么想法吗?

@Cherniv:这给了我一个非常相似的东西,[object Object]。然后我需要 foo[0],我们又回到原点了。 - sergserg
5个回答

8

试一下这个:

$("#btnCopy").on("click",function(){
    var $img = $("#firstDiv").children("img").clone();
    $("#secondDiv").append($img);
});

working fiddle here: http://jsfiddle.net/GbF7T/


0

试试这个:

$(".copy").on("click",function(){
    $("#a_clone").clone().appendTo("#b_clone"); 
});

虽然这段代码可能回答了问题,但是提供有关如何和/或为什么解决问题的附加上下文将改善答案的长期价值。您可以在帮助中心找到有关编写良好答案的更多信息:https://stackoverflow.com/help/how-to-answer。祝你好运 - nima

0

试试这个。

$('.copy').click(function() {
    imageElement = $(this).siblings().find('img').eq(0);

 $("div.item").append(imageElement.clone());


 });

无法工作,与上述相同;这给我返回[object Object] - sergserg

0

由于您的img位于另一个div中,您可以使用.html()函数。

像这样:

$('.copy').on('click', function(){
    var orig = $(this).children('img');
    var otherDiv = $('#otherDiv');
    otherDiv.html(orig.html());
});

0

试试这个

    $('.copy').click(function() {
         var imageElement = $('#div1').html();
         $('#div2').html(imageElement);
    }

如果您不需要替换#div2中的内容,请使用"append"或"prepend"而不是html。例如:$('#div2').prepend(imageElement);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接