我在使用树视图过滤器时遇到问题。我做了以下方法:
var tree =
[{
id: "Arvore",
text: "Arvore",
children: [
{
id: "Folha_1",
text: "Folha 1",
children: [
{
id: "Folha_1_1",
text: "Folha 1.1",
children: [
{
id: "dd",
text: "abc"
}
]
}
]
},
{
id: "Folha_2",
text: "Folha 2"
},
{
id: "Folha_3",
text: "Folha 3"
},
{
id: "Folha_4",
text: "Folha 4"
},
{
id: "Folha_5",
text: "Folha 5"
}
]
}];
filterData: function filterData(data, value) {
return data.filter(function(item) {
if (item.children) item.children = filterData(item.children, value);
return item.text.indexOf(value) > -1;
});
},
但是当我输入文本时,例如Folha 1.1
,我希望它返回Arvore > Folha 1 > Folha 1.1
,但该函数只返回第一个子节点。我能做什么?
这样的事情应该有效。如果你想返回路径,那么你需要检查项目是否匹配OR是否有子项(意味着子项匹配)。
var tree =
[{
id: "Arvore",
text: "Arvore",
children: [
{
id: "Folha_1",
text: "Folha 1",
children: [
{
id: "Folha_1_1",
text: "Folha 1.1",
children: [
{
id: "dd",
text: "abc"
}
]
}
]
},
{
id: "Folha_2",
text: "Folha 2"
},
{
id: "Folha_3",
text: "Folha 3"
},
{
id: "Folha_4",
text: "Folha 4"
},
{
id: "Folha_5",
text: "Folha 5"
}
]
}];
function filterData(data, value) {
return data.filter(function(item) {
if (item.children) item.children = filterData(item.children, value);
return item.text.indexOf(value) > -1 || (item.children && item.children.length > 0);
});
}
filterData(tree, "Folha 1.1")
console.log(tree)
我找到了解决方案
filterData: function filterData(data, value, forceShow) {
return data.filter(function(item) {
if (item.children) item.children = filterData(item.children, value, item.text.indexOf(value) > -1);
return forceShow || (item.text.indexOf(value) > -1 || (item.children && item.children.length > 0));
});
},