每列点击搜索的数据表
DataTables on click search per column
我试图在点击相关元素时激活每列的搜索。
我设法在点击时获得了搜索框,但它没有执行搜索
我不是 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();
}
});
});
}
});
有没有办法让代码更短?
谢谢
在您将 keyup change clear
事件处理程序附加到输入时,输入不存在。您需要改用委托事件。
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();
}
});
});
}
您可以使用 jQuery's one
method 附加一个只会调用一次的事件处理程序。您还应该尽可能避免为同一输入创建多个 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()));
});
});
我试图在点击相关元素时激活每列的搜索。
我设法在点击时获得了搜索框,但它没有执行搜索
我不是 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();
}
});
});
}
});
有没有办法让代码更短?
谢谢
在您将 keyup change clear
事件处理程序附加到输入时,输入不存在。您需要改用委托事件。
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();
}
});
});
}
您可以使用 jQuery's one
method 附加一个只会调用一次的事件处理程序。您还应该尽可能避免为同一输入创建多个 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()));
});
});