jQuery克隆问题

时间:2012-08-20 11:47:48

标签: javascript jquery

我正在尝试通过创建唯一ID来将行克隆到内容中,但我遇到了一些问题。

HTML:

<div class="content">
    <div id="email-container" class="email-container">
            <input type="text" value="" placeholder="Email">
            <input type="text" value="" placeholder="Email">
            <input type="text" value="" placeholder="Email">
            <span class="plus-button">+</span>
        </div>
</div>

JavaScript的:

$('.plus-button').click(function(){
    $('.email-container').clone().insertAfter(".email-container").end();
    $('.email-container').find('.plus-button').text('-').not(':last-child');
});

请在下面找到我的小提琴:

http://jsfiddle.net/meetravi/GCRVS/3/

我正在尝试克隆#email-container并将其添加到.content内并清除文本框值,并且还需要将.plus-button值更改为“ - ”,但最后一行除外。

3 个答案:

答案 0 :(得分:4)

试试这个: 而且你不需要id#email-container。

$(document).on('click', '.plus-button', function(){
    var content = $(this).text();
    if(content == '+'){
        $(this).parent().clone(true, true).insertAfter($(this).parent());
        $('.email-container').each(function(){
            if(!$(this).is(':last-child')){
                $(this).find('.plus-button').html('-');
            }
        });
    }
    else{
        $(this).parent().remove();

    }
});

编辑:我做了一个主要的编辑插入if / else也解决了删除问题......

EDIT2:它必须说insertAfter($(this).parent()

答案 1 :(得分:3)

<div class="content">
    <div id="email-container" class="email-container">
        <input class="1" type="text" value="" placeholder="Email">
        <input class="1" type="text" value="" placeholder="Email">
        <input class="1" type="text" value="" placeholder="Email">
        <span class="plus-button">+</span>
    </div> 
</div>

$(document).ready(function()
{
    $('.plus-button').click(AddNewRow);
});

function AddNewRow(event)
{
   var clone = $('.email-container').last().clone().appendTo('.content');
   clone.children('.1').val(''); //delete all values of your clone
   clone.children('.plus-button').bind('click', AddNewRow);

   var btn = $(this).parent().find('.plus-button');  //The cloned button
   btn.text('-');
   btn.removeClass('plus-button');
   btn.addClass('minus-button');
   btn.unbind('click');  //unbind the "old" click event
   btn.click(RemoveRow);
}


function RemoveRow(event)
{
    $(this).parent().remove();
}

这应该可以解决问题。 TIPP:当你在DOM中创建新元素时,你应该手动绑定项目或使用“on”

编辑:删除.live()因为其弃用

答案 2 :(得分:2)

对于动态生成的元素,应该委派click事件,您可以使用on方法,请注意我已从标记中删除了ID属性,因为ID应该是唯一的并且在文档中具有相同的ID属性使它无效。请尝试以下方法:

$(document).on('click', '.plus-button', function(){
    $('.email-container:last').clone().insertAfter(".email-container:last")
    $('.email-container:not(:last)').find('.plus-button').attr('class', 'remove').text('-');
});

$(document).on('click', '.remove ', function(){
    $(this).closest('.email-container').remove();
});

Fiddle