[英]jstree jquery how to iterate through all nodes
我正在嘗試遍歷 jstree 中樹視圖中的每個節點。 樹視圖有 4 層深,但我似乎無法超過 1 層。 以下是用於迭代的jQuery。
$("#myTree").bind('ready.jstree', function (event, data) {
$('#myTree li').each(function () {
// Perform logic here
}
});
});
這是一個 jsfiddle 說明了我的觀點。 請幫助我如何遍歷 jstree 中的每個節點。
這將在您的.each
循環的平面數組中獲取您樹的所有子項。
$("#tree").bind('ready.jstree', function(event, data) {
var $tree = $(this);
$($tree.jstree().get_json($tree, {
flat: true
}))
.each(function(index, value) {
var node = $("#tree").jstree().get_node(this.id);
var lvl = node.parents.length;
var idx = index;
console.log('node index = ' + idx + ' level = ' + lvl);
});
});
另一種方法是在嘗試訪問 dom 中的節點之前打開它們,然后關閉它們:
$("#tree").bind('ready.jstree', function (event, data) {
$(this).jstree().open_all(); // open all nodes so they are visible in dom
$('#tree li').each(function (index,value) {
var node = $("#tree").jstree().get_node(this.id);
var lvl = node.parents.length;
var idx = index;
console.log('node index = ' + idx + ' level = ' + lvl);
});
$(this).jstree().close_all(); // close all again
});
“節點”是一個重載的術語。 你是指 HTML 節點還是只是用於定義 jstree 中每個節點的 JSON 數據? 我需要遍歷 jstree 以提取每個 jstree 節點中 ID 字段的值。 如果這就是你所需要的,還有一個更簡單的方法:
var v =$("#tree").jstree(true).get_json('#', {'flat': true});
for (i = 0; i < v.length && i < 10; i++) {
var z = v[i];
alert("z[id] = " + z["id"]);
}
我想要一種遍歷 jsTree 節點的庫方式,所以我將其寫入jstree.js
文件:
each_node: function(callback) {
if (callback) {
var id, nodes = this._model.data;
for (id in nodes) {
if (nodes.hasOwnProperty(id) /*&& id !== $.jstree.root*/) {
callback.call(this, nodes[id]);
}
}
}
},
(注意:我使用的是jsTree 3.3.4 ,並且在get_json
函數定義之后的第3712
行插入了上面的代碼。)
在代碼中,我可以像這樣遍歷樹的節點:
$("#myTree").jstree(true).each_node(function (node) {
// 'this' contains the jsTree reference
// example usage: hide leaf nodes having a certain data attribute = true
if (this.is_leaf(node) && node.data[attribute]) {
this.hide_node(node);
}
});
var jsonNodes = $('#jstree').jstree(true).get_json('#', { flat: true });
$.each(jsonNodes, function (i, v) {
if (true) {
// Following line will hide the check box on some condition
// $("#" + v.id + "_anchor i.jstree-checkbox").toggle(false);
// it will print the id
console.log(v.id);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.