【发布时间】:2017-04-22 13:23:27
【问题描述】:
我有一个与this question 相似但不同的查询。
不同之处在于我试图通过行而不是列上的数据属性进行过滤。 tr 元素,而不是 td 元素。这包含一个主键,我正在尝试删除重复项。重复的行可能在实际列数据中有所不同,所以我不能那样做。键是由下划线分隔的三个数字字段的组合。
<tr data-primarykey="12345678_12_34"><td>...
然后,在页面加载时调用的 javascript 函数内...
var rows = [];
$.fn.DataTable.ext.search.push(
function( settings, data, dataIndex, rowObj, counter ) {
if(counter === 0) rows = [];
// I want rowkey to be the data-primarykey attribute of the tr element
var rowkey = table.row(dataIndex).data('primarykey');
// If we've seen the row before (already in the array), filter it out.
// Otherwise, return true and add it to the array
if ($.inArray(rowkey,rows) > -1) return false;
else {
rows.push(rowkey);
return true;
}
}
);
我怀疑部分问题是table 对象没有在任何地方定义。此过滤器适用于多个表,因此如果可能,它需要是当前正在过滤的任何表。每个表都有一个唯一的id,但共享一个class 属性。
2016 年 12 月 12 日更新
我在使用实际数据属性的版本方面取得了一些进展。这个版本有一个工作的table DataTable 对象,我认为正确地获取了行并将其转换为 jquery。但是,尝试在undefined 中获取数据属性。
$.fn.DataTable.ext.search.push(
function( settings, data, dataIndex, rowObj, counter ) {
if(counter === 0) rowkeys = [];
// I want rowkey to be the data-primarykey attribute of the tr element
var tableID = $(settings.nTable).attr("id");
var table = $('#'.tableID).DataTable(); // Correct DataTable
//var row = table.rows(dataIndex).nodes().to$(); // Correct row?
var rowkey = table.rows(dataIndex).nodes().to$().data("primarykey");
console.log('key: '+rowkey); // Shows 'key: undefined' in console.
// If we've seen the row before (already in the array), filter it out.
// Otherwise, return true and add it to the array
if ($.inArray(rowkey,rowkeys) > -1) return false;
else {
rowkeys.push(rowkey);
return true;
}
}
);
【问题讨论】:
-
您的控制台中是否有任何错误表明
table未定义? -
没有。只有我用来填充表格的 ajax 调用。我尝试在过滤器中使用
console.log,但这也没有出现,尽管如果我将它包含在页面加载功能中,它会出现。我实际上在想我的问题可能是我打破了 ajax 加载,所以表格永远不会重绘...... -
@jonmrich 你是说
table应该自动可用吗?DataTable.ext.search.push()上的文档不是很全面,也没有提及。 -
你需要设置
table变量。像这样:var table = $("#mydatatable").DataTable({ }) -
@AntonChanning 我已经修复了
I'm stuck on is getting the value of that attribute from within the filter handler的那部分。我会给你我的答案
标签: jquery datatables html5-data