我不确定是否应该对“爱丁堡”进行硬编码,或者您是否希望用户能够指定自己的值,所以这里是硬编码的解决方案,用户可以使用 cmets-提供值选项:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
var exclude = 'Edinburgh'; // User provided value: $("#user-exclude-field").val();
if(!exclude) return true; // nothing to exclude, so all rows should be included
var re = new Regexp("\\b" + exclude + "\\b", "i"); // using the \b word boundary meta-character to match only "Edinburgh" and not "NewEdinburgh" (typo on purpose)
return !re.test(data.office); // return TRUE (i.e. include this row in the search results) if the "office" attribute of the current row data does NOT match our excluded word
});
更新
因此,根据您的评论,这是一个示例小提琴:
https://jsfiddle.net/bjLzkjnc/
更新 2
因此,您希望能够过滤所有包含单词的项目,或过滤所有不包含该单词的行。更新小提琴:jsfiddle.net/1xh3kys5
这里的神奇之处在于filter 变量。之前它只是一个布尔变量,因为我们想要跟踪两种状态:“包含 SC”与“显示所有内容”。但是现在您实际上具有三种状态:“包含 SC”、“显示所有内容”和“显示所有不包含 SC 的内容”......所以布尔值已经不够用了。
有几种方法可以解决这个问题,但我使用了一个过滤器对象,以便您最终可以轻松添加更多过滤器:
var filters = {
sc: {active: false, re: new RegExp("\\bSC\\b", "i"), include: true}
};
这里的filters对象只有一个属性,一个filter,叫做“sc”。该属性本身就是一个对象,它有一些属性可以让我们代表我们所有的三种状态:
-
active 是打开/关闭这个特殊的“sc”过滤器。因此,当您想要显示所有行时,只需将其设置为 false,然后停用 sc 过滤器即可。
-
include 是我们的布尔值,用于控制是否要包含或排除包含单词“SC”的行。
-
re 只是我们想要过滤行时使用的正则表达式。
当我们现在过滤行时,我们只是使用正则表达式来确定特定行是否包含“SC”。
var includes_sc = filters.sc.re.test(data[2]);
return (filters.sc.include ? includes_sc : !includes_sc);
因此,基于“include”属性的值,并将其存储在名为includes_sc 的变量中。如果当前过滤器想要包含“SC”的所有行,我们将按原样返回includes_sc。另一方面,如果我们想要所有不包含“SC”的行,我们返回includes_sc 的倒数(!includes_sc)。
希望这会有所帮助!