参考(AddNode: http://blog.csdn.net/qq_25628235/article/details/51719917,deleteNode:http://blog.csdn.net/u012718733/article/details/53288584)
Bootstrap treeview增加或者删除节点
功能说明:展开节点时,新增子节点。选中节点时,删除节点
第一步:在bootstrap-treeview.js文件中,在Tree主函数return {/*在这里添加addNode的入口*/ 和 {/*在这里添加deleteNode的入口*/}
//添加节点
addNode: $.proxy(this.addNode, this),
//删除节点
deleteNode: $.proxy(this.deleteNode, this),
setDeleteNode: $.proxy(this.setDeleteNode, this),
第二步:添加Tree的prototype方法
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) {
if (node.nodes == null) node.nodes = [];
if (options.node) {
node.nodes.push(options.node);
};
}; Tree.prototype.deleteNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
var parentNode = this.getParent(node);
this.setDeleteNode(parentNode, node, options);
}, this));
}; Tree.prototype.setDeleteNode = function (node, deletenode, options) {
if (node.nodes != null) {
for (var i = node.nodes.length - 1; i >= 0; i--) {
var mynode = node.nodes[i];
if (mynode.id === deletenode.id) {
node.nodes.splice(i, 1);
}
}
this.setInitialStates({ nodes: this.tree }, 0);
this.render();
}
};
第三步 调用
<div id="tree1"></div>
Json数据
function getTree() {
var data = [
{
text: "p1",
id: '0',
nodes: [
{ text: "p1-1", id: '1' },
{ text: "p1-2", id: '2' },
{ text: "p1-3", id: '3' },
{
text: "p1-4",
id: '4',
nodes: [
{
text: 'p1-1-1',
id: '5'
}
]
}
]
}
];
return data;
}
绑定Treeview
$("#tree1")
.treeview({
data: getTree(),
showIcon: false,
showCheckbox: true,
onhoverColor: "#E8E8E8",
showBorder: false,
showTags: true,
highlightSelected: true,
highlightSearchResults: false,
selectedBackColor: "#8D9CAA",
levels: 2,
onNodeSelected: function(event, data) {
alert(data.nodeId);
if (data.nodes === undefined || data.nodes === null) {
return;
}
$("#tree1").treeview("deleteNode", [data.nodeId, { silent: true }]);
//nodeData是checkedNode或者selectedNode,选中或者checked这个节点, 该节点如果有父节点的话就会被删除。
},
onNodeExpanded:
function(event, data) {
$.ajax({
type: "Post",
url: "/Bootstrap/GetExpandJson?id=" + data.id,
dataType: "json",
success: function (result) {
for (var index = 0; index < result.length; index++) {
var item = result[index];
$("#tree1")
.treeview("addNode",
[
data.nodeId,
{ node: { text: item.text, id: item.id }, silent: true }
]);
}
}
});
}
});