Как получить данные строки из KTDatatable с помощью jQuery

#javascript #jquery #datatables #metronic

Вопрос:

Я пытаюсь получить данные строки, нажав на кнопку в той же строке. Проверяя документацию metronic, есть событие, которое возвращает весь набор данных, используемый для создания таблицы, но нет ничего, что указывало бы способ извлечения данных из одной строки. В той же документации они указывают, что необходимо установить флажок, затем установите флажок, чтобы позже попытаться выполнить поиск по названию столбцов. Я уже сделал это, и он всегда возвращает пустое значение

мой код таков:

 var KTDatatableRemoteAjaxDemo = function () {
    // Private functions

    // basic demo
    var demo = function () {

        var datatable = $('#kt_datatable').KTDatatable({
            // datasource definition
            data: {
                type: 'remote',
                source: {
                    read: {
                        url: 'Horarios/GetHorarios',
                        // sample custom headers
                        // headers: {'x-my-custom-header': 'some value', 'x-test-header': 'the value'},
                        map: function (raw) {
                            // sample data mapping
                            var dataSet = raw;
                            if (typeof raw.data !== 'undefined') {
                                dataSet = raw.data;
                            }
                            return dataSet;
                        },
                    },
                },
                pageSize: 10,
                serverPaging: true,
                serverFiltering: false,
                serverSorting: false,
            },

            // layout definition
            layout: {
                scroll: false,
                footer: false,
                spinner: {
                    message: true,
                    message: "CARGANDO DATOS"
                }
            },
            translate: {
                records: {
                    processing: 'ESPERE POR FAVOR',
                    noRecords:'SIN REGISTROS PARA MOSTRAR'
                },
                toolbar: {
                    pagination: {
                        items: {
                            default: {
                                first: 'Primero',
                                prev: 'Anterior',
                                next: 'Siguiente',
                                last: 'Último',
                                more: 'Más páginas',
                                input: 'Número de página',
                                select: 'Selecciona página1'
                            },
                            info: 'Mostrando {{start}} - {{end}} de {{total}} registros'
                        }
                    }
                }
            },

            // column sorting
            sortable: true,

            pagination: true,
            detail: {
                title: 'VER DIAS',
                content: subTableInit,
            },
            

            // columns definition
            columns: [{
                field: 'consecutivo',
                title: '',
                sortable: 'asc',
                width: 50,
                type: 'number',
                selector: false,
                textAlign: 'center',
            }, {
                    field: 'checkbox',
                    title: '',
                    template: '{{consecutivo}}',
                    sortable: false,
                    width: 20,
                    textAlign: 'center',
                    selector: { class: 'kt-checkbox--solid' },
                },
            
                {
                field: 'fechaInicial',
                    title: 'FECHA INICIAL',
                    type: 'date',
                    format: 'MM/DD/YYYY',
                    textAlign: 'center',
                },
                {
                    field: 'fechaFinal',
                    title: 'FECHA FINAL',
                    type: 'date',
                    format: 'MM/DD/YYYY',
                    textAlign: 'center',
                }, 
                {
                    field: 'horaInicial',
                    title: 'HORA INICIAL',
                    textAlign: 'center',
                },
                {
                    field: 'horaFinal',
                    title: 'HORA FINAL',
                    textAlign: 'center',
                }, 
                {
                field: 'status',
                title: 'ESTATUS',
                    autoHide: false,
                    textAlign: 'center',
                // callback function support for column rendering
                template: function (row) {
                    var status = {
                        
                        1: {
                            'title': 'ACTIVO',
                            'class': ' label-light-success'
                        },                        
                        0: {
                            'title': 'INACTIVO',
                            'class': ' label-light-danger'
                        }
                    };
                    return '<span class="label font-weight-bold label-lg '   status[row.status].class   ' label-inline">'   status[row.status].title   '</span>';
                },
                },
                {
                    field: '',
                    title: 'ACCIONES',
                    sortable: false,
                    overflow: 'visible',
                    autoHide: false,
                    
                    template: function () {
                        return '<a class="btn btn-sm btn-clean btn-icon mr-2" id="editHorario" title="Editar horario">
                                <span class="svg-icon svg-icon-md">
                                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                                        <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                            <rect x="0" y="0" width="24" height="24"/>
                                            <path d="M8,17.9148182 L8,5.96685884 C8,5.56391781 8.16211443,5.17792052 8.44982609,4.89581508 L10.965708,2.42895648 C11.5426798,1.86322723 12.4640974,1.85620921 13.0496196,2.41308426 L15.5337377,4.77566479 C15.8314604,5.0588212 16,5.45170806 16,5.86258077 L16,17.9148182 C16,18.7432453 15.3284271,19.4148182 14.5,19.4148182 L9.5,19.4148182 C8.67157288,19.4148182 8,18.7432453 8,17.9148182 Z" fill="#000000" fill-rule="nonzero" transform="translate(12.000000, 10.707409) rotate(-135.000000) translate(-12.000000, -10.707409) "/>
                                            <rect fill="#000000" opacity="0.3" x="5" y="20" width="15" height="2" rx="1"/>
                                        </g>
                                    </svg>
                                </span>
                            </a>
                        ';
                    },
                },
            ],

        });
        
        
        //----------------------------------------------------------------------------------

        function subTableInit(e) {
            $('<div/>').attr('id', 'child_data_ajax_'   e.data.consecutivo).appendTo(e.detailCell).KTDatatable({
                data: {
                    type: 'remote',
                    source: {
                        read: {
                            url: '/Horarios/GetDias',
                            params: {
                                // custom query params
                                consecutivo: e.data.consecutivo
                            },
                        },
                    },
                    
                },
                pagination:false,
                // layout definition
                layout: {
                    scroll: false,
                    footer: false,

                    // enable/disable datatable spinner.
                    spinner: {
                        type: 1,
                        theme: 'default',
                        message: true,
                        message:'CARGANDO DIAS'
                    },
                },

                sortable: false,

                // columns definition
                columns: [
                     {
                        field: 'dia',
                        title: 'Dias',
                        textAlign: 'center',
                        template: function (row) {
                            var dia = {

                                1: {
                                    'title': 'LUNES',
                                    'class': ' label-light-primary'
                                },
                                2: {
                                    'title': 'MARTES',
                                    'class': ' label-light-success'
                                },
                                3: {
                                    'title': 'MIÉRCOLES',
                                    'class': ' label-light-info'
                                },
                                4: {
                                    'title': 'JUEVES',
                                    'class': ' label-light-warning'
                                },
                                5: {
                                    'title': 'VIERNES',
                                    'class': ' label-light-danger'
                                }

                            };



                            return '<span class="label font-weight-bold label-lg '   dia[row.dia].class   ' label-inline">'   dia[row.dia].title   '</span>';
                        },
                    }, {
                        field: 'totalAudienciasJunta',
                        title: 'TOTAL AUDIENCIAS DE LA JUNTA',
                        textAlign: 'center',
                        
                    }, {
                        field: 'totalAudienciasRadicaciones',
                        title: 'TOTAL AUDIENCIAS DE RADICACIONES',
                        textAlign: 'center',
                    },
                    
                    {
                        field: '',
                        width: 125,
                        title: 'ACCIONES',
                        sortable: false,
                        overflow: 'visible',
                        autoHide: false,
                        template: function () {
                            return '<a href="javascript:;" class="btn btn-sm btn-clean btn-icon mr-2" title="Editar día">
                                <span class="svg-icon svg-icon-md">
                                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                                        <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                            <rect x="0" y="0" width="24" height="24"/>
                                            <path d="M8,17.9148182 L8,5.96685884 C8,5.56391781 8.16211443,5.17792052 8.44982609,4.89581508 L10.965708,2.42895648 C11.5426798,1.86322723 12.4640974,1.85620921 13.0496196,2.41308426 L15.5337377,4.77566479 C15.8314604,5.0588212 16,5.45170806 16,5.86258077 L16,17.9148182 C16,18.7432453 15.3284271,19.4148182 14.5,19.4148182 L9.5,19.4148182 C8.67157288,19.4148182 8,18.7432453 8,17.9148182 Z" fill="#000000" fill-rule="nonzero" transform="translate(12.000000, 10.707409) rotate(-135.000000) translate(-12.000000, -10.707409) "/>
                                            <rect fill="#000000" opacity="0.3" x="5" y="20" width="15" height="2" rx="1"/>
                                        </g>
                                    </svg>
                                </span>
                            </a>
                        ';
                        },
                    },],
            });
        }
    };

    return {
        // public functions
        init: function () {
            demo();
        },
    };
}();

$('#kt_datatable').on('click', 'tbody tr #editHorario', function (e) {
    var row = $('#kt_datatable').KTDatatable().row($(this).parents('tr').data());

    
});
 

Ответ №1:

Я нашел решение, несколько примитивное, но эффективное. Как только событие click выполнено, я добавляю класс выбора KDatatable, чтобы позже использовать его функцию выбора, и беру html-элементы, которые он возвращает мне, чтобы сделать это через цикл for, просматриваю элементы и беру данные, которые помещают их в свойство aria-label.

 $('#kt_datatable').on('click', 'tbody tr #editHorario', function (e) {
$(this).closest('tr').addClass('datatable-row-active');
var row = datatable.getSelectedRecords();
$(this).closest('tr').removeClass('datatable-row-active');
let seleccion = []
for (let i = 0; i < row.length; i  ) {
seleccion = row[i].getElementsByTagName('td');
}
});