如果搜索栏为空,则重绘表

Redraw table if search bar is empty

本文关键字:搜索栏 如果      更新时间:2023-09-26

基于此讨论,将下面的代码添加到我的JS代码中,以便通过按回车键而不是键控或延迟来触发过滤。

jQuery.fn.dataTableExt.oApi.fnSetFilteringPressEnter = function (oSettings) {
    var _that = this;
    this.each(function (i) {
        $.fn.dataTableExt.iApiIndex = i;
        var $this = this;
        var anControl = $('input', _that.fnSettings().aanFeatures.f);
        anControl.unbind('keyup').bind('keypress', function (e) {
            if (e.which == 13) {
                $.fn.dataTableExt.iApiIndex = i;
                _that.fnFilter(anControl.val());
            }
        });
        return this;
    });
    return this;
}
/* Example call */
$(document).ready(function() {
    $('.dataTable').dataTable().fnSetFilteringPressEnter();
} );

现在我想做的是,当用户从搜索栏中删除关键字时,我想重新绘制表格。目前,如果不按回车按钮,它不会重新绘制。我怎样才能达到这个结果?

我认为在

键盘的 keyup 事件上是安全的,不像仅在enter按键时触发。

anControl.off('keyup').on('keypress', function (e) {
        $.fn.dataTableExt.iApiIndex = i;
        _that.fnFilter(anControl.val());
});

另外,请注意,我使用了on()off()进行委派,而不是从jQuery 1.7开始不推荐使用的bindunbind

或者,您可以为特定情况创建一个完全不同的处理程序,其中文本框中的所有关键字都将被删除。

    anControl.off('keyup').on('keypress', function (e) {
        if (e.which == 13) {
            $.fn.dataTableExt.iApiIndex = i;
            _that.fnFilter(anControl.val());
        }
        if(anControl.val().length == 0) {
               //redraw table
        }
    });

mayb 你可以通过使用 jquery 的 .blur 事件来实现你需要的东西。 当文本框失去焦点时.. 简单地将过滤器设置为空字符串,如下所示。

this.each(function (i) {
        $.fn.dataTableExt.iApiIndex = i;
        var $this = this;
        var anControl = $('input', _that.fnSettings().aanFeatures.f);
        anControl.unbind('keyup').bind('keypress', function (e) {
            if (e.which == 13) {
                $.fn.dataTableExt.iApiIndex = i;
                _that.fnFilter(anControl.val());
            }
        });
        anControl.blur(function(){
            _that.fnFilter('');
        });
        return this;
    });
    return this;