如何用jsTree.js实现结点展开和收拢时图标的变化

JavaScript013

如何用jsTree.js实现结点展开和收拢时图标的变化,第1张

您好,很高兴为您解答。

<%@ page language="java" contentType="text/html charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge"><!--  IE使用它所支持的最新版本-->

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>tree</title>

<link href="../css/bootstrap.min.css" rel="stylesheet">

<link href="../css/style.min.css" rel="stylesheet">

<link href="../css/font-awesome.min.css" rel="stylesheet">

</head>

<body>

  <div id="myTree">

    <ul>

      <li>Root 1</li>

      <li>Root 2

        <ul>

          <li id="child1">

            <a>child 1</a>

            <ul>

              <li>child 1-1</li>

              <li>child 1-2</li>

            </ul>

          </li>

          

          <li>child 2</li>

          <li>child 3</li>

        </ul>

      </li>

      <li>Root 3</li>

    </ul>

  </div>

  

  <script src="../js/jquery.min.js"></script>

  <script src="../js/bootstrap.min.js"></script>

  <script src="../js/jstree.min.js"></script>

  <script>

  $(function () { 

$('#myTree').jstree()

$('#myTree').on("changed.jstree", function (e, data) {

  console.log(data.selected)

  }) 

$('button').on('click', function () {

      $('#myTree').jstree(true).select_node('child1')

      $('#myTree').jstree('select_node', 'child1')

      $.jstree.reference('#myTree').select_node('child1')

  }) 

  })

  </script>

  

</body>

</html>

如若满意,请点击右侧【采纳答案】,如若还有问题,请点击【追问】

希望我的回答对您有所帮助,望采纳!

~ O(∩_∩)O~

有3种方法:

用is_parent( node)方法, node传节点ID或节点对象, 有下级节点则返回true.

用is_leaf(node)方法, 此方法表示是否为最末级, 刚好和is_parent相反.

在事件中获取node对象, 其中node.child为包含所有直接子节点的数组, node.child.length === 0 则没有下级节点.

示例:

html

<div id="tree"></div>

JavaScript

var $tree = $('#tree')

$tree.jstree({

    core: {

        data: [

            { id: '1', parent: '#', text: "1" },

            { id: '2', parent: '1', text: "11" },

            { id: '3', parent: '1', text: "12" },

            { id: '4', parent: '2', text: "111" }

        ]

    }

})

$tree.on('ready.jstree', function () {

    //jQuery风格

    $tree.jstree('is_parent', '2') //true

    $tree.jstree('is_leaf', '2') //false

    

    //使用jstree实例对象操作

    var tree = $tree.jstree(true)

    tree.is_parent('4') //false

    tree.is_leaf('4') //true 

    

    //注意: jstree的初始化是一个异步过程, 如果上述代码没有放在初始化完成的事件中,将不会得到正确的结果,因为执行代码时,jstree还没生成.

})

//jstree事件中的应用

$tree.on('select_node.jstree', function (e, data) {

    var node = data.node

    if(node.child.length > 0)

        console.log('此节点有下级节点')

        

    var tree = data.instance

    if(tree.is_parent(node)) //这里无需tree.is_parent(node.id), is_parent方法可以node对象作为参数.

        console.log('此节点有下级节点')     

})