Bootstrap-treeview动态加载子节点

本文介绍了如何在Bootstrap-treeview中实现动态添加和删除子节点的功能。首先需要引入Bootstrap-treeview的js和css文件,然后修改bootstrap-treeview.js源码,添加`addNode`、`deleteNode`和`deleteChildrenNode`方法。接着详细展示了新增加和删除方法的代码实现,最后给出了调用这些方法的例子,如删除当前节点下所有子节点和添加子节点的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、引入Bootstrap-treeview的js和css

bootstrap-treeview.js
bootstrap-treeview.css

2、修改bootstrap-treeview.js源码

2.1、在var Tree = function (element, options)方法的return中添加如下代码:

// 添加节点方法
addNode: $.proxy(this.addNode, this),
// 删除节点方法
deleteNode: $.proxy(this.deleteNode, this),
deleteChildrenNode: $.proxy(this.deleteChildrenNode, this),

2.2、在var Tree = function (element, options)方法下面新增添加和删除的方法,代码如下:

// 给节点添加子节点
	Tree.prototype.addNode = function (identifiers, options) {
	    this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
	            this.setAddNode(node, options);
	    }, this));
 
	    this.setInitialStates({ nodes: this.tree }, 0);
	    this.render();
	};
 
	//添加子节点
	Tree.prototype.setAddNode = function (node, options) {
        /*若当前要插入子节点的父节点没有任何子节点,则将[]赋给父节点,
	      否则node.nodes会出现undefined的错误*/
	    if (node.nodes == null) {
	    	node.nodes = [];
	    }
	    if (options.node) {
	        node.nodes.push(options.node);
	    }
	};
	/**
	 * 删除节点,若是根节点不能删除
	 * 获取节点的父节点,
	 * 根据Id删除父节点nodes集合中的自己
	 * 刷新父节点
	 * @param identifiers
	 * @param options
	 */
	Tree.prototype.deleteNode = function (identifiers, options) {
	    this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
	        var parentNode = this.getParent(node);
	        if(parentNode && parentNode.nodes != null ){
	            for(var i = parentNode.nodes.length-1; i >= 0; i--){
	                if(parentNode.nodes[i].nodeId == node.nodeId){
	                    parentNode.nodes.splice(i, 1);
	                }
	            }
	            this.setInitialStates({ nodes: this.tree }, 0);
	            this.render();
	        }else{
	            console.log('根节点不能删除');
	        }
	    }, this));
	};
	/**
	 * 删除子节点
	 * @param node
	 * @param options
	 */
	Tree.prototype.deleteChildrenNode = function (identifiers, options) {
	    this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
	        if ( node.nodes != null){
	            node.nodes = null;
	            this.setInitialStates({ nodes: this.tree }, 0);
	            this.render();
	        }
	    }, this));
	};

3、调用添加和删除子节点的方法

//删除当前节点下的所有子节点
$("#itemtree").treeview("deleteChildrenNode", id);	
//添加子节点
var addNodes = new Array();
addNodes[0] = id;
addNodes[1] = {node: {text: "新加的菜单", href: "001005" }};
$("#itemtree").treeview("addNode", addNodes);
//当然也可以写成这样
$("#itemtree").treeview("addNode", [id,{node: {text: "新加的菜单", href: "001005" }}]);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值