如何在.draw()之后保持jQuery DataTables滚动位置 [英] How to maintain jQuery DataTables scroll position after .draw()

查看:156
本文介绍了如何在.draw()之后保持jQuery DataTables滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将jQuery Datatables插件用于一个小表(12行).某些<input type="text" ...字段允许编辑.当输入字段失去焦点时,我需要验证其值并可能更改字段值.我无法在不随后发出.draw()的情况下获取修改后的输入字段值以供DataTables识别,但这会导致表格滚动到表格顶部.

I am using jQuery Datatables plugin for a smal table (12 rows). Some <input type="text" ... fields allow editing. When the input field loses focus I need to validate its value and possibly change the field value. I haven't been able to get modified input field values to be recognized by DataTables without issuing a .draw() afterwards, but this causes the table to scroll to the top of the table.

发出.draw()之后,是否有办法保持当前滚动位置?

Is there a way of maintaining the current scroll position after issuing a .draw()?

$('#mytable').on('blur', 'input', function (e) {

    var inputFieldId = this.id;
    var inputFieldVal = $(this).val();

    { ... perform validation of field value ... }

    $('#mytable').DataTable().rows().invalidate().draw();
});

编辑

我看到有人试图做我同样的事情,他们指出以下代码对他们有用.这似乎是完成我所需要的一种非常简单的方法,但是我总是自己获得scrollTop = 0.有人看到我如何获取当前所选行的行索引吗?

I saw someone trying to do the same thing I am and they indicated that the following code worked for them. This seems like a very simple way of accomplishing what I need, but I'm always getting scrollTop = 0 myself. Anyone see how I can get the row index of the currently selected row?

var scrollPos = $(".dataTables_scrollBody").scrollTop();
$('#mytable').DataTable().rows().invalidate().draw(false);
$(".dataTables_scrollBody").scrollTop(scrollPos);

推荐答案

我认为您无法做到这一点,但是您可以改用Callback函数:

I don't think you can do that, but you can use the Callback function instead:

$(document).ready(function() {
    var selected = [];

    $("#example").dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "scripts/ids-arrays.php",
        "rowCallback": function( row, data ) {
            if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
                $(row).addClass('selected');
            }
        }
    });

    $('#example tbody').on('click', 'tr', function () {
        var id = this.id;
        var index = $.inArray(id, selected);

        if ( index === -1 ) {
            selected.push( id );
        } else {
            selected.splice( index, 1 );
        }

        $(this).toggleClass('selected');
    } );
} );

Ref: https://datatables.net/examples/server_side/select_rows.html

这篇关于如何在.draw()之后保持jQuery DataTables滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆