基于 Pilan 的回答 (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;
}
现在,自定义的数据表搜索(和排序)将使用这个代表值,如下所示:
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:
// 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
]
});