search
HomeWeb Front-endJS Tutorialjquery ztree implements fuzzy search function_jquery

This article shares two examples of jquery ztree implementing fuzzy search function for your reference. The specific content is as follows

In the official demo code of ztree:
Find nodes based on parameters
Modify the above file into the following code

<!DOCTYPE html>
<HTML>
<HEAD>
  <TITLE> ZTREE DEMO - getNodeByParam / getNodesByParam / getNodesByParamFuzzy</TITLE>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="../../../css/demo.css" type="text/css">
  <link rel="stylesheet" href="../../../css/zTreeStyle/zTreeStyle.css" type="text/css">
  <script type="text/javascript" src="../../../js/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.core-3.5.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.exhide-3.5.js"></script>
<!--<script type="text/javascript" src="../../../js/jquery.ztree.excheck-3.5.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.exedit-3.5.js"></script>-->
  <SCRIPT type="text/javascript">
     
    var setting = {
      data: {
        key: {
          title: "t"
        },
        simpleData: {
          enable: true
        }        
      }
    };
 
    var zNodes =[
      { id:1, pId:0, name:"节点属性搜索演示 1", t:"id=1"},
      { id:11, pId:1, name:"关键字可以是名字", t:"id=11"},
      { id:12, pId:1, name:"关键字可以是level", t:"id=12"},
      { id:13, pId:1, name:"关键字可以是id", t:"id=13"},
      { id:14, pId:1, name:"关键字可以是各种属性", t:"id=14"},
      { id:2, pId:0, name:"节点搜索演示 2", t:"id=2"},
      { id:21, pId:2, name:"可以只搜索一个节点", t:"id=21"},
      { id:22, pId:2, name:"可以搜索节点集合", t:"id=22"},
      { id:23, pId:2, name:"搜我吧", t:"id=23"},
      { id:3, pId:0, name:"节点搜索演示 3", t:"id=3"},
      { id:31, pId:3, name:"我的 id 是: 31", t:"id=31"},
      { id:32, pId:31, name:"我的 id 是: 32", t:"id=32"},
      { id:33, pId:32, name:"我的 id 是: 33", t:"id=33"}
    ];
 
    function focusKey(e) {
      if (key.hasClass("empty")) {
        key.removeClass("empty");
      }
    }
    function blurKey(e) {
      if (key.get(0).value === "") {
        key.addClass("empty");
      }
    }
    var lastValue = "", nodeList = [], fontCss = {};
    function clickRadio(e) {
      lastValue = "";
      searchNode(e);
    }
    function searchNode(e) {
      var zTree = $.fn.zTree.getZTreeObj("treeDemo");
      if (!$("#getNodesByFilter").attr("checked")) {
        var value = $.trim(key.get(0).value);
        var keyType = "";
        if ($("#name").attr("checked")) {
          keyType = "name";
        } else if ($("#level").attr("checked")) {
          keyType = "level";
          value = parseInt(value);
        } else if ($("#id").attr("checked")) {
          keyType = "id";
          value = parseInt(value);
        }
        if (key.hasClass("empty")) {
          value = "";
        }
        if (lastValue === value) return;
        lastValue = value;
        if (value === "") {
          zTree.showNodes(zTree.transformToArray(zTree.getNodes())) ;
          return;
        }
 
        if ($("#getNodeByParam").attr("checked")) {
          var node = zTree.getNodeByParam(keyType, value);
          if (node === null) {
            nodeList = [];
          } else {
            nodeList = [node];
          }
        } else if ($("#getNodesByParam").attr("checked")) {
          nodeList = zTree.getNodesByParam(keyType, value);
        } else if ($("#getNodesByParamFuzzy").attr("checked")) {
          nodeList = zTree.getNodesByParamFuzzy(keyType, value);
        }
      } else {
        updateNodes(false);
        nodeList = zTree.getNodesByFilter(filter);
      }
      /**不查询父级
      for(var x = 0 ; x<nodeList.length ; x++){
        if(nodeList[x].isParent){
          nodeList.splice(x--,1);
        }
      }
      */
      nodeList = zTree.transformToArray(nodeList);
      updateNodes(true);
 
    }
    function updateNodes(highlight) {
      var zTree = $.fn.zTree.getZTreeObj("treeDemo");
      var allNode = zTree.transformToArray(zTree.getNodes());
      zTree.hideNodes(allNode);
      for(var n in nodeList){
        findParent(zTree,nodeList[n]);
      }
       
      zTree.showNodes(nodeList);
    }
     
    function findParent(zTree,node){
      zTree.expandNode(node,true,false,false);
      var pNode = node.getParentNode();
      if(pNode != null){
        nodeList.push(pNode);
        findParent(zTree,pNode);
      }
       
    }
     
     
    function getFontCss(treeId, treeNode) {
      return (!!treeNode.highlight) &#63; {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
    }
    function filter(node) {
      return !node.isParent && node.isFirstNode;
    }
 
    var key;
    $(document).ready(function(){
      $.fn.zTree.init($("#treeDemo"), setting, zNodes);
      key = $("#key");
      key.bind("focus", focusKey)
      .bind("blur", blurKey)
      .bind("propertychange", searchNode)
      .bind("input", searchNode);
       
      $("#name").bind("change", clickRadio);
      $("#level").bind("change", clickRadio);
      $("#id").bind("change", clickRadio);
      $("#getNodeByParam").bind("change", clickRadio);
      $("#getNodesByParam").bind("change", clickRadio);
      $("#getNodesByParamFuzzy").bind("change", clickRadio);
      $("#getNodesByFilter").bind("change", clickRadio);
       
       
    });
     
  </SCRIPT>
</HEAD>
 
<BODY>
<h1 id="根据参数查找节点">根据参数查找节点</h1>
<h6 id="文件路径-core-searchNodes-html">[ 文件路径: core/searchNodes.html ]</h6>
<div class="content_wrap">
  <div class="zTreeDemoBackground left">
    <ul id="treeDemo" class="ztree"></ul>
  </div>
  <div class="right">
    <ul class="info">
      <li class="title"><h2 id="getNodeByParam-getNodesByParam-getNodesByParamFuzzy-方法操作说明">1、getNodeByParam / getNodesByParam / getNodesByParamFuzzy 方法操作说明</h2>
        <ul class="list">
        <li class="highlight_red">使用 zTreeObj.getNodeByParam / getNodesByParam / getNodesByParamFuzzy / getNodeByTId 方法,详细请参见 API 文档中的相关内容</li>
        <li><p>搜索试试看:<br/>
            属性值( value ):<input type="text" id="key" value="" class="empty" /><br/>
            属性( key ):<input type="radio" id="name" name="keyType" class="radio first" checked /><span>name (string)</span><br/>
            <input type="radio" id="level" name="keyType" class="radio" style="margin-left:68px;" /><span>level (number) ... 根节点 level = 0</span><br/>
            <input type="radio" id="id" name="keyType" class="radio" style="margin-left:68px;" /><span>id (number)</span><br/>
            方法:<input type="radio" id="getNodeByParam" name="funType" class="radio first" /><span>getNodeByParam</span><br/>
            <input type="radio" id="getNodesByParam" name="funType" class="radio" style="margin-left:36px;" /><span>getNodesByParam</span><br/>
            <input type="radio" id="getNodesByParamFuzzy" name="funType" class="radio" style="margin-left:36px;" checked /><span>getNodesByParamFuzzy (only string)</span><br/>
            <input type="radio" id="getNodesByFilter" name="funType" class="radio" style="margin-left:36px;" /><span>getNodesByFilter (参考本页源码中 function filter)</span><br/>
          </p>
        </li>
        </ul>
      </li>
      <li class="title"><h2 id="setting-配置信息说明">2、setting 配置信息说明</h2>
        <ul class="list">
        <li>不需要对 setting 进行特殊设置</li>
        </ul>
      </li>
      <li class="title"><h2 id="treeNode-节点数据说明">3、treeNode 节点数据说明</h2>
        <ul class="list">
        <li class="highlight_red">请注意各个方法使用时保证传入查找的参数类型与设定要查找的属性的类型一致</li>
        </ul>
      </li>
    </ul>
  </div>
</div>
</BODY>
</HTML>

In this way, the fuzzy search display function can be easily realized.

The second Ztree tree structure fuzzy search implementation method, the specific content is as follows

function expand_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    treeObj.expandAll(true);
  }
   
  
  function close_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.transformToArray(treeObj.getNodes());
    var nodeLength = nodes.length;
    for (var i = 0; i < nodeLength; i++) {
      if (nodes[i].id == '0') {
        //根节点:展开         treeObj.expandNode(nodes[i], true, true, false);
      } else {
        //非根节点:收起         treeObj.expandNode(nodes[i], false, true, false);
      }
    }
  }
   
  
  function search_ztree(treeId, searchConditionId){
    searchByFlag_ztree(treeId, searchConditionId, "");
  }
   
  
  function searchByFlag_ztree(treeId, searchConditionId, flag){
    //<1>.搜索条件     var searchCondition = $('#' + searchConditionId).val();
    //<2>.得到模糊匹配搜索条件的节点数组集合     var highlightNodes = new Array();
    if (searchCondition != "") {
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
    }
    //<3>.高亮显示并展示【指定节点s】     highlightAndExpand_ztree(treeId, highlightNodes, flag);
  }
   
  
  function highlightAndExpand_ztree(treeId, highlightNodes, flag){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    //<1>. 先把全部节点更新为普通样式     var treeNodes = treeObj.transformToArray(treeObj.getNodes());
    for (var i = 0; i < treeNodes.length; i++) {
      treeNodes[i].highlight = false;
      treeObj.updateNode(treeNodes[i]);
    }
    //<2>.收起树, 只展开根节点下的一级节点     close_ztree(treeId);
    //<3>.把指定节点的样式更新为高亮显示,并展开     if (highlightNodes != null) {
      for (var i = 0; i < highlightNodes.length; i++) {
        if (flag != null && flag != "") {
          if (highlightNodes[i].flag == flag) {
            //高亮显示节点,并展开             highlightNodes[i].highlight = true;
            treeObj.updateNode(highlightNodes[i]);
            //高亮显示节点的父节点的父节点....直到根节点,并展示             var parentNode = highlightNodes[i].getParentNode();
            var parentNodes = getParentNodes_ztree(treeId, parentNode);
            treeObj.expandNode(parentNodes, true, false, true);
            treeObj.expandNode(parentNode, true, false, true);
          }
        } else {
          //高亮显示节点,并展开           highlightNodes[i].highlight = true;
          treeObj.updateNode(highlightNodes[i]);
          //高亮显示节点的父节点的父节点....直到根节点,并展示           var parentNode = highlightNodes[i].getParentNode();
          var parentNodes = getParentNodes_ztree(treeId, parentNode);
          treeObj.expandNode(parentNodes, true, false, true);
          treeObj.expandNode(parentNode, true, false, true);
        }
      }
    }
  }
   
  
  function getParentNodes_ztree(treeId, node){
    if (node != null) {
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      var parentNode = node.getParentNode();
      return getParentNodes_ztree(treeId, parentNode);
    } else {
      return node;
    }
  }
   
  
  function setFontCss_ztree(treeId, treeNode) {
    if (treeNode.id == 0) {
      //根节点       return {color:"#333", "font-weight":"bold"};
    } else if (treeNode.isParent == false){
      //叶子节点       return (!!treeNode.highlight) &#63; {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
    } else {
      //父节点       return (!!treeNode.highlight) &#63; {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
    }
  }
 
  //==============HTML==============  
  
class="padd" style="padding-bottom: 0px;">
    
class="input-append row-fluid" style="margin-bottom: 0px;">
      "search_condition" type="text" placeholder="请输入搜索条件" class="span8" style="font-size:12px"/>
      "button" class="btn btn-info" onclick="search_ztree('dep_tree', 'search_condition')">搜索
  
"dep_tree" class="ztree">

The above is the code for jquery ztree to implement fuzzy search function. I hope it will be helpful to everyone's learning.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),