You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:实现TreeView按节点Title与Description过滤并展示父级层级

Solution for Nested TreeView Filtering with Parent Node Preservation

Let's break down how to fix your TreeView filtering issue. The core problem with your current code is that it only checks the current item's title and doesn't account for nested child matches or the description field. We need a recursive approach to check both the node itself and all its descendants, plus ensure parent nodes stay visible if any of their children match the query.

Original TreeView Structure

First, let's visualize your existing tree for clarity:

  • Item 1 (id:132)
    • Item 1.1 (id:133)
      • Item 1.1.1 (id:134)
  • Item 2 (id:135)
  • Item 3 (id:136)
    • Item 3.1 (id:137)

Step 1: Create a Recursive Match Checker

We'll build a helper function that recursively checks if a node (or any of its children) matches the query against either title or description:

// Helper function to check if a node or its descendants match the query
function hasMatchingDescendant(item, query) {
  // Check current node's title and description
  const currentNodeMatches = item.title.includes(query) || item.description.includes(query);
  
  // Recursively check all child nodes
  const childNodeMatches = item.nodes.some(child => hasMatchingDescendant(child, query));
  
  // Return true if either the current node or any child matches
  return currentNodeMatches || childNodeMatches;
}

Step 2: Update the Visibility Function

Now modify your visible function to use this helper. It will show all nodes when there's no query, and only show nodes that either match themselves or have matching descendants when a query exists:

this.visible = function(item) {
  // If no query exists, show everything
  if (!this.query || this.query.length === 0) {
    return true;
  }
  
  // Check if this node or any of its children match the query
  return hasMatchingDescendant(item, this.query);
};

How This Works

  • When you search for a term that matches Item 1.1.1, the helper function will return true for Item 1.1.1, then propagate up: Item 1.1 will return true (because its child matches), and Item 1 will also return true (because its child matches). This keeps the full hierarchy intact.
  • The function checks both title and description, so matches in either field will trigger visibility.
  • If a node has no matching descendants and doesn't match itself, it will be hidden.

Edge Case Notes

  • Empty description fields won't cause false matches because includes(query) will only return true if the query is present (and your code already checks that query.length > 0).
  • This works for any depth of nested nodes, not just one level of parent-child.

内容的提问来源于stack exchange,提问作者Andre Leoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:23:20