简体   繁体   English

每列点击搜索的数据表

[英]DataTables on click search per column

I'm trying to active the seach per column on click of the related element.我正在尝试在单击相关元素时激活每列的搜索。

I managed to get the search box on click but it doesn't perform the search我设法在点击时获得了搜索框,但它没有执行搜索

I'm not that expert with javascript and jQuery but this is my code:我不是 javascript 和 jQuery 的专家,但这是我的代码:

    // Setup - add a text input to each footer cell
    $('#DataTable tfoot th').each(function () {

        var title = $(this).text();
        $(this).click(function (event) {
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
            $(this).unbind('click');
        });

    });

    // DataTable
    var table = $('#DataTable').DataTable({
        initComplete: function () {
            // Apply the search
            this.api().columns().every(function () {
                var that = this;

                $('input', this.footer()).on('keyup change clear', function () {
                    if (that.search() !== this.value) {
                        that
                            .search(this.value)
                            .draw();
                    }
                });
            });
        }
    });

Is there also a way to make the code shorter?有没有办法让代码更短?

Thank you谢谢

The input doesn't exist at the point where you attach your keyup change clear event handler to it.在您将keyup change clear事件处理程序附加到它的地方,输入不存在。 You'll need to use delegated events instead.您需要改用委托事件。

initComplete: function() {
    this.api().columns().every(function() {
        var that = this;
        $(this.footer()).on('keyup change clear', 'input', function() {
            if (that.search() !== this.value) {
                that.search(this.value).draw();
            }
        });
    });
}

You can use jQuery's one method to attach an event handler which will only be called once.您可以使用jQuery 的one方法来附加一个事件处理程序,该处理程序只会被调用一次。 You should also avoid creating multiple jQuery wrappers for the same input where you can.您还应该尽可能避免为同一输入创建多个 jQuery 包装器。

$('#DataTable tfoot th').each(function () {
    var $this = $(this);
    $this.one("click", function (event) {
        $this.empty().append($('<input/>').attr("type", "search").attr("placeholder", "Search " + $this.text()));
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM