0

我想在添加输入并将其删除后,通过 jQuery 排列输入名称元素数组中的数字,但在删除输入后对我不起作用。如何解决?

演示:http: //jsfiddle.net/mUMdW/

我的代码:

html:

<div class="ch">
        <a href="#" class="adding">Add</a>
</div>
<p class="ffdd"></p>

jQuery:

function removeidx(clss, type){
    var remove = $(this).closest(clss);
    remove.fadeOut('slow', function () {
        $(this).remove(); // or change next line to  $('.RowCheck:visible')
        $(clss).each(function (idx) {
            var checkBoxes = $('input[type="'+type+'"]',this);
            checkBoxes.each(function(i) {
              var str = $(this).attr('name');  
              var currentIdx = parseInt(str.match(/\d+/)[0], 10);  
              $(this).attr('name', str.replace(currentIdx,idx));
           })
        });
    });
}
$(document).on('click change', 'a.adding', function(e) {
    e.preventDefault();
    var idx = $('.Row').length;
    $('.ffdd').append('<div class="Row"> <input name="arr['+idx+'][]" type="text" value=""> <a href="#" class="remove_row" title="remove this row">Remove</a></div>');   
});
$('.ffdd').on('click','a', function(e){
    $(this).closest('.Row').remove();
    removeidx('.ffdd', 'text');
})
4

1 回答 1

1

我猜您想在删除后重新编号输入,以便数组由连续数字组成。

我重写了一些东西,其中包括重新编号函数,使用与父函数相关的索引。

function removeidx(context, clss, type) {
    var remove = $(context).closest(clss);
    remove.fadeOut('slow', function () {
        $(this).remove();
        var idx = 0;
        $(clss).each(function () {
            var checkBoxes = $('input[type="' + type + '"]', this);
            checkBoxes.each(function () {
                var name = $(this).attr('name');
                name = name.replace(/\d+/, idx);
                $(this).attr('name', name);
                idx = idx + 1;
            });
        });
    });
}

$(document).on('click change', 'a.adding', function (e) {
    e.preventDefault();
    var idx = $('.Row').length;
    $('.ffdd').append('<div class="Row"> <input name="arr[' + idx + '][]" type="text" value=""> <a href="#" class="remove_row" title="remove this row">Remove</a></div>');
});

$('.ffdd').on('click', 'a', function (e) {
    removeidx(this, '.Row', 'text');
})

你可以在那里看到一个工作版本:http: //jsfiddle.net/8sVWp/

于 2013-01-30T10:45:06.420 回答