【问题标题】:How to count from 1 when remove a row ajax?删除行ajax时如何从1开始计数?
【发布时间】:2021-09-12 21:02:40
【问题描述】:

我必须创建一个功能,用户可以使用输入字段添加和删除行。问题是,当删除一行或多行然后再次添加时,我需要在每行不正确的顺序(1.、2.、3.等)前面有一个行索引(数字)。我可以添加行,但我无法正确计数,因为如果我删除它们,那么计数从 4 开始,但我需要 1,或者如果第二行被删除,那么我需要 2 而不是 4。

我已经用 append() 做到了,到目前为止一切都很好,但我还需要在每一行前面加上 row cont。我有一个计数器,但假设我添加了 1 行,它给出了数字 1 和 2。如果我删除第二行并再次添加另一个,现在计数是 1 和 3

注意“添加”按钮只有一个,并且与append()分开;

我有三行,分别是 1、2 和 3

现在我将删除其中一个。比如我删除第2行。我看这个demo,

这不应该发生。它应该分别显示数字 1 和 2。

<script>
    $(document).ready(function() {
        $('#educationalForm').submit(function(event){
            event.preventDefault();
            var formData = new FormData($('#educationalForm')[0]);
            $.ajax({
                url:'{{ route('educational.store') }}',
                method: 'POST',
                data: formData,
                cache:false,
                contentType: false,
                processData: false,
                success:function(data){
                    const variables = ['grade', 'major', 'end'];
                    variables.forEach(variable => {
                        if(data[variable] === null) data[variable] = '';
                    });
                    const newRowNum = $('#educationalForm tr').length + 2;
                    let html = '' +
                        '<tr>'+
                        '<td class="fw-normal" id="demo">'+ (newRowNum) +'</td>'+
                        '<td class="fw-normal">'+data.grade+'</td>'+
                        '<td class="fw-normal">'+data.major+'</td>'+
                        '<td class="fw-normal">'+data.end+'</td>'+
                        '<td>'+
                        '<form method="post" id="educational-destroy">'+
                        '@csrf'+
                        '@method('DELETE')'+
                        '<div class="btn-group">'+
                        '<a data-id="'+data.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
                        '<button data-id="'+data.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
                        '</div>'+
                        '</form>'+
                        '</td>'+
                        '</tr>';
                    $('#educationalTable').append(html);
                    $('#educationalForm').trigger('reset');
                },
            });
        });

        showEducationals();

        function showEducationals() {
            $.get('{{ route('educational.index') }}', function (data) {
                $('#educationalTable').html("");
                $.each(data, function (key, val) {
                    const variables = ['grade', 'major', 'end'];
                    variables.forEach(variable => {
                        if(val[variable] === null) val[variable] = '';
                    });
                    $('#educationalTable').append('<tr>'+
                        '<td class="fw-normal">'+ (key+1) +'</td>'+
                        '<td class="fw-normal">'+val.grade+'</td>'+
                        '<td class="fw-normal">'+val.major+'</td>'+
                        '<td class="fw-normal">'+val.end+'</td>'+
                        '<td>'+
                        '<form method="post" id="educational-destroy">'+
                        '@csrf'+
                        '@method('DELETE')'+
                        '<div class="btn-group">'+
                        '<a data-id="'+val.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
                        '<button data-id="'+val.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
                        '</div>'+
                        '</form>'+
                        '</td>'+
                        '</tr>'
                    );
                });
            });
        }

        $(document).on('click', '#educationalEdit', function(event) {
            event.preventDefault();
            var id = $(this).data('id');
            $.ajax({
                type:'get',
                url:'/educational/'+id+'/edit',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success:function (data) {
                    console.log(data);
                    $('#id').val(data.educational.id);
                    $('#edit_grade').val(data.educational.grade);
                    $('#edit_major').val(data.educational.major);
                    $('#edit_avg').val(data.educational.avg);
                    $("input[name='edit_start']").val(data.educational.start);
                    $("input[name='edit_end']").val(data.educational.end);
                    $('#edit_docPlaceName').val(data.educational.docPlaceName);
                    $('#edit_thesisTitle').val(data.educational.thesisTitle);
                    $('#edit_docPlaceCountry').val(data.educational.docPlaceCountry);
                    $('#edit_docPlaceCity').val(data.educational.docPlaceCity);
                },
            });
        });

        $(document).on('click', '#educationalUpdate', function(event) {
            event.preventDefault();
            var id = $('#id').val();
            var file = $('#edit_upload_doc').prop('files')[0];
            var formData = new FormData($('#educationalFormUpdate')[0]);
            formData.append('file', file);
            $.ajax({
                type: 'POST',
                url: '/educational/'+id,
                dataType: 'JSON',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    console.log(response);
                    $('#educationalModal').modal('hide');
                    showEducationals();
                },
            });
        });

        $(document).on('click', '#educationalDestroy', function(event) {
            event.preventDefault();
            $.ajax({
                url:'educational/'+$(this).data('id'),
                type: 'DELETE',
                dataType: 'json',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    $('#educationalsTable').html('');
                    showEducationals();
                },
                error: function(response) {
                    console.log(response);
                },
            });
        });
    });
</script>

所以总的来说,在元素被删除之前,我可以正确计数。如果我有 3 行,我的计数是 1. 2. 3. 但如果我删除所有这些并再次添加 3 行,我得到 4. 5. 6. 但我需要 1. 2. 3. 再次

【问题讨论】:

    标签: html jquery ajax


    【解决方案1】:

    您应该在每次重新渲染整个表格时重置计数器。

    您可以将count 移动到您的渲染函数内部,但这并不是绝对必要的,因为jQuery's each function 已经提供了一个索引(您将其命名为key),您可以使用它来代替count

    因此,你可以这样做:

    function showEducationals() {
        $.get('{{ route('educational.index') }}', function (data) {
            $('#educationalTable').html("");
            $.each(data, function (key, val) {
                const variables = ['grade', 'major', 'end'];
                variables.forEach(variable => {
                    if(val[variable] === null) val[variable] = '';
                });
                $('#educationalTable').append('<tr>'+
                    '<td class="fw-normal">'+ (key+1) +'</td>'+ // using key instead of count
    

    请注意,我还删除了 id=demo。这是因为您正在使用id=demo(在'&lt;td class="fw-normal" id="demo"&gt;'+count+++'&lt;/td&gt;'+)创建多个单元格,理想情况下,id 应该是唯一的。

    关于添加新行,使用表实际拥有的行数,而不是 i

    $('#educationalForm').submit(function(event){
        event.preventDefault();
        var formData = new FormData($('#educationalForm')[0]);
        $.ajax({
            url:'{{ route('educational.store') }}',
            method: 'POST',
            data: formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                const variables = ['grade', 'major', 'end'];
                variables.forEach(variable => {
                    if(data[variable] === null) data[variable] = '';
                });
                const newRowNum = $('#educationalTable tr').length + 1; // added this
                let html = '' +
                    '<tr>'+
                    '<td class="fw-normal">'+ (newRowNum) +'</td>'+ // edited this
    

    此外,您应该删除 icount 变量,因为它们不再需要:

    showEducationals();
    let i;                 // remove this
    let count = 1;         // remove this
    function showEducationals() {
        // ...
                );
                i = count  // remove this
            });
    

    【讨论】:

    • 谢谢,有问题。当我删除行时。我清空桌子。但是我会从2开始添加另一个。我想从1开始。
    • 我已经修改了答案来处理这个问题。请查看(您可以从顶部重新阅读)。
    • 我在控制台看到这个错误Uncaught TypeError: $(...).size is not a function
    • 如果.size(),请尝试.length
    • 使用const newRowNum = $('#educationalTable tr').length + 1; 而不是const newRowNum = $('#educationalForm tr').length + 2;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2023-04-07
    • 1970-01-01
    • 2017-02-28
    • 2021-07-30
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多