问题
Is there a way to have custom markup or add additional html elements to some of the nodes.
For example, we want to add an arrow (link) right after the node text for all the nodes under a path, and when user click on the arrow, open the context menu. I know the context menu can be opened using the right click, but the requirement is to have an arrow after the node and clicking on the arrow should open the context menu.
Is there a way to customize or add additional html elements to selective tree nodes, and programmatically open the context menu or link click event.
回答1:
The best way to achieve this is using a plugin, you can take a look at similar sample plugins here: https://github.com/vakata/jstree/blob/master/src/misc.js (the questionmark plugin for example).
Here is a rough demo, modify as needed: http://jsfiddle.net/DGAF4/490/
(function ($, undefined) {
"use strict";
var img = document.createElement('IMG');
img.src = "http://jstree.com/tree-icon.png";
img.className = "jstree-contextmenubtn";
$.jstree.plugins.contextmenubtn = function (options, parent) {
this.bind = function () {
parent.bind.call(this);
this.element
.on("click.jstree", ".jstree-contextmenubtn", $.proxy(function (e) {
e.stopImmediatePropagation();
$(e.target).closest('.jstree-node').children('.jstree-anchor').trigger('contextmenu');
}, this));
};
this.teardown = function () {
this.element.find(".jstree-contextmenubtn").remove();
parent.teardown.call(this);
};
this.redraw_node = function(obj, deep, callback, force_draw) {
obj = parent.redraw_node.call(this, obj, deep, callback, force_draw);
if(obj) {
var tmp = img.cloneNode(true);
obj.insertBefore(tmp, obj.childNodes[2]);
}
return obj;
};
};
})(jQuery);
回答2:
With jstree version 3.3.0 you can use node_customize plugin
$("#category-tree").jstree({
core: {
data: nodes
},
node_customize: {
default: function(el, node) {
$(el).find('a').append(arrowHtml)
}
},
plugins: ['node_customize']
})
来源:https://stackoverflow.com/questions/30083636/jstree-custom-node-markup