jquery只能克隆一次

时间:2010-04-25 12:18:52

标签: jquery clone unique

我有一系列像这样的div:

<div id="available-posts">
    <div class="post" id="unique_id">
      <a href="#" class="addme">Add</a> Some text
    </div>

    <div class="post" id="unique_id">
      <a href="#" class="addme">Add</a> Some text
    </div>
</div>

对于每个div,unique_id是不同的数字。

现在我有一个像这样的新空div

<div class="related-posts"></div>

我在那里克隆物品。

问题是我想检查一个项目是否已被克隆。如果是我想阻止它再次被克隆。

这就是我克隆物品的方式:

    // clone it
$('.addme').live('click', function() {
        $(this).parents('div.thepost').clone().fadeIn('normal').appendTo('#related-posts').find('a.addme').html('Remove').removeClass('addme').addClass('removeme');
        return false;
}); 

// remove it
$('.removeme').live('click', function() {
        $(this).parents('div.thepost').fadeOut('normal', function() {$(this).remove(); });
        return false;
}); 

换句话说,我希望克隆列表只包含唯一的项目。不是例如相同帖子的2个克隆。

*编辑:我正在使用live coz,第一个列表(可用帖子)通过AJAX调用填充。

1 个答案:

答案 0 :(得分:1)

请继续检查是否已存在具有此ID的div:

$('.addme').live('click', function() {
        var post = $(this).parents('div.thepost');
        var postId = post.attr("id");
        if ( $("#related-posts").find( "#" + postId ).size() ) return;

        post.clone().fadeIn('normal').appendTo('#related-posts').find('a.addme').html('Remove').removeClass('addme').addClass('removeme');
        return false;
});