克隆时使用jQuery删除第一个类

时间:2011-02-03 09:31:29

标签: javascript jquery html

我写了一个简单的函数来克隆一个字段:

在线演示:http://jsfiddle.net/5yVPg/

HTML:

<div id="main">
       <a id="add-input" href="#">+ add</a>

       <p class="child">
         <input type="text" name="user[]" />
         <a href="#" class="icon-delete">delete</a>
       </p>
</div>

JS:

$(document).ready(function () {
    $('#add-input').click(function () {
        var newField = $('.child').clone()
        newField.toggle().attr('class', '')
        registerRemoveHandlers(newField, '.icon-delete')
        $(this).parent().append(newField)
        return false
    })
    function registerRemoveHandlers(el, class) {
        $(el).find(class).click(function () {
            $(this).parents('p:first').remove()
            return false
        })
    }
})

我想从第一个输入中删除删除图标,我试过:

$('p.child .icon-delete:first').css('display','none')

但是没有为所有输入显示删除图标。

PS:如果我可以优化上面的代码,我会很高兴:)

4 个答案:

答案 0 :(得分:2)

请看一下这个:

// Keep a single clone of the original
var clonedField = $('.child').clone(),
    main = $('#main');

// Add in the delete <a> to the cloned field
$('<a>', {
    text: 'delete',
    class: 'icon-delete',
    href: '#',
    click: function(){
        $(this).parent().remove();
        return false;
    }
}).appendTo(clonedField);

// Clone the cloned original and append it back to the list
$('#add-input').click(function() {
    main.append(clonedField.clone());
    return false;
});

代码更简单,更容易理解,然后你有什么,并且应该按照你的预期工作。

在jsfiddle上查看:http://jsfiddle.net/5ZFh6/

答案 1 :(得分:2)

  
$(function() {
    $('#add-input').click(function() {
        $('<p><input type="text" name="user[]" /> ' + 
          '<a href="#" class="icon-delete">delete</a></p>').appendTo('#main');
    });

    // just for sake...
    $('.icon-delete').live('click',
    function() {
        $(this).parent().fadeOut(500,
        function() {
            $(this).remove();
        });
    });
});

<强>陷阱:

  1. 你为什么要克隆?
  2. 为什么要将删除按钮放在首位?

答案 2 :(得分:1)

我认为这样可以解决问题....... $('p.child .icon-delete:first').css('display','none')隐藏了.icon-delete的所有p.child。在您的情况下,所有p.child都是.icon-delete

的孩子
$('p.child:first .icon-delete').css('display','none')

答案 3 :(得分:0)

$('#add-input').bind('click',function ()
{
    var newField = $('.child').clone();
    newField.toggle().attr('class', '');
    registerRemoveHandlers(newField, '.icon-delete');
    $('p.child:last').after(newField); //append after not cloned child

    newField.parent().children('p').find('a').show(); //show all 'delete' label
    newField.prev().find('a').hide(); //hide label from the first child which is right the one before our clone

    return false;
});

http://jsfiddle.net/K7F5K/