基于
皮兰
的答案(
JQuery DataTables Search within Input/Select With Complex DOM Structure
)但是,通过一些额外的调整,以及重构来允许搜索和排序,这里是最后的答案。
策略:首先定义一个返回
给定TD单元的“代表字符串”
. 然后,把它用在
搜索和排序
,以支持这两种操作。
// Define the custom utility function that brings back a "Representative String" for a TD for DataTables' Search & Sort
function getRepresentativeStringForTDContent(el) {
// Will store concenatenated string for this TD cell
var all_search_values = "";
// NOTE: "el" is the content of TD, which could be either
// (1) input field(s) themselves -- one or multiple, or
// (2) wrapping element(s) in which we need to find() -- one or multiple
$(el).each(function (index) {
var inputsInput = $(this).is('input') ? $(this) : $(this).find('input');
var inputsSelect = $(this).is('select') ? $(this) : $(this).find('select');
inputsInput.each( function( i, e) {
// Text Inputs added by value
all_search_values += $(e).val();
});
inputsSelect.each( function( i, e) {
// Select Inputs added by Selected Option text (not value)
all_search_values += $(e).find('option:selected').text();
});
});
return all_search_values;
}
现在,定制的DATABATE搜索(和排序)将使用该代表值如下:
1。搜索
// Define the DataTable custom Search function for Input/Select fields
$.fn.dataTableExt.ofnSearch['html-input'] = function(el) {
return getRepresentativeStringForTDContent(el);
};
2。排序
// Define the DataTable custom Sort function for Input/Select fields
$.fn.dataTable.ext.order['html-input'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return getRepresentativeStringForTDContent($(td).html());
});
};
将2个自定义搜索和排序功能应用于数据表:
// DataTable creation
var table = $("#exampleTable").DataTable({
columnDefs: [
{ "type": "html-input", "targets": [3, 4, 5] }, // Search Logic
{ "orderDataType": "html-input", type: "string", "targets": [3, 4, 5] } // Sort Logic
]
});