开发者

help with clone and appendTo in jquery

Here is my DOM:

    <div class="group">
        <div class="comment">
            <button class="addLink">Add link</button>
        </div>

        <div class="link">
            <button class="removeLink">Remove link</button>
        </div>
    </div>

I wanna click on the button.addLink and it will copy the div.link and append it as last child in div.group.

i started out with this code but got stuck.

 $(this).parent().parent().children(':last').clone().appendTo();

i dont know how to write appendTo. cause i want it to be appended to div.group but i cant just type 开发者_JAVA百科it as 'div.group' cause there will be a lot of other div.group so i have to select it from a relational point of view.

could someone help me out here?


$(this).parent().parent().children(':last').clone().appendTo($(this).parent().parent());

Or a bit nicer:

var $parent = $(this).parent().parent();
$parent.children(':last').clone().appendTo($parent);

appendTo() accepts a parameter as target where the elements should be appended to.

You should read the API documentation, it is well explained.


$("button.addLink").click(function() {
    var self = $(this);
    var linkDiv = self.parent().next().clone();
    self.parent().parent().append(linkDiv);    
});

Here's a Working Demo. Click on the Preview button and try the code out.


Try:

$(".addLink").click(function() {
    var clone = $(this).parent().next("div.link").clone();
    $(this).closest(".group").append(clone);
});


Try .parents()

$('.addlink').click(function(){
   var parent = $(this).parents('div.group');
   parent.children(':last').clone().appendTo(parent);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜