我使用 Jstree 插件
我有一个疑问, 我想知道是否可以按多个单词进行过滤,如下所示:
具有以下结构:
Root node
One Child Node
node 1
node 2
node 3
Two Child Node
node 4
node 5
node 6
通过以下搜索:
一个子节点1
带来结果:
Root node
One Child Node
node 1
有这个可能吗?
编辑 1 搜索代码:
$('#jstree-q').keyup(function () {
if(to) { clearTimeout(to); }
to = setTimeout(function () {
var v = $('#jstree-q').val();
$('#jstree').jstree(true).search(v);
}, 250);
});
最佳答案
我刚刚发现您的查询与 jstree 相关,但与此同时,我花了一个愉快的半小时在 jquery 中为此构建了一个可能的解决方案。无论如何我都会发布它,因为它可能对你有帮助。
演示在这里:http://jsfiddle.net/sifriday/ezhj1Lbt/
我使用的方法是为 li 元素构建一条路径;例如,“节点 1”元素的路径为“根节点/一个子节点/节点 1”。然后,我将搜索短语分解为单词,因此您的短语“One Child node 1”给出数组 ['One', 'Child', 'node', 1']。然后,我仅显示路径与数组中每个单词匹配的节点。这是构建路径的 jquery 代码:
function process(li, path) {
$.data($(li).get(0), 'path', path)
$(li).children("ul").each(function(jdx, ul) {
$(ul).children("li").each(function(idx, child_li) {
process($(child_li), path + " / " + $(child_li).children("span").text())
});
});
}
$(".search-tree>li").each(function(idx, li) {
process($(li), $(li).children("span").text())
});
这是处理搜索的 jquery 代码(区分大小写,因此您应该搜索“One Child”而不是“one child”):
$("#search-input").keyup(function() {
// Hide everything to start with
$(".search-tree li").hide()
// Extract all the words from the search box
var words = $("#search-input").val().split(" ");
// Now go through the tree, and show <li>s that match the words
$(".search-tree").find("li").each(function(idx, li) {
// We only test the nodes, ie, the <li>s with no children
if ($(li).find("ul").length == 0) {
// Assume we will show the node...
var show = true;
// ...but decide to hide it if one of the words doesn't exist in the path
$(words).each(function(jdx, word) {
if ($.data($(li).get(0), 'path').indexOf(word) == -1) {
show = false
}
})
// If the verdict was show=true, show this node and its parents
if (show) {
$(li).show()
$(li).parents("li").show()
}
}
});
});
我不知道 jstree 的方法,但您可以将这种方法重新修改为 Samuel 上面提到的 $.jstree.defaults.search.search_callback。
关于javascript - 过滤包含多个单词的过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849861/