gpt4 book ai didi

javascript - knockout js,从 TreeView 中选择的项目中找到所有父节点id

转载 作者:行者123 更新时间:2023-11-30 17:28:22 24 4
gpt4 key购买 nike

我们正在创建一个具有 n(任意)层的 TreeView 。

我拍了this tree solution ,但现在我遇到了一个问题。

我们想从所选节点获取所有父节点 id

谁能帮我们解决这个问题?

最佳答案

据我所知,您可以获得当前选定节点的 id,它已经是父 id 的串联。

替换

  <div data-bind="with: selected">
Selected Node: <span data-bind="text: name"></span>
</div>

  <div data-bind="with: selected">
Selected Node: <span data-bind="text: name"></span>
Ids: <span data-bind="text: id"></span>
</div>

如果您想要一个包含所有父 ID 的数组,您可以执行以下操作:

  1. 为每个树节点添加一个parent属性(parent)并填充到构造函数中
  2. 添加父 ID 数组 (parentIds)
  3. 创建一个将遍历所有 TreeNode 并填充 parentIds 数组的函数

检查此代码(1. & 2.):

function TreeNode(values) {
var self = this;
ko.mapping.fromJS(values, { children: { create: createNode }}, this);
this.expanded = ko.observable(false);
for (var i = 0; i < this.children().length; i++)
this.children()[i].parent = this;
this.parentIds = [];
this.collapsed = ko.computed(function() {
return !self.expanded();
})
}

还有这个 (3.):

function setParents(rootNode) {
if (ko.isObservable(rootNode.children) && rootNode.children().length)
for (var i = 0; i < rootNode.children().length; i++) {
if (rootNode.children()[i].parent)
rootNode.children()[i].parentIds = rootNode.children()[i].parent.parentIds.slice(0);
rootNode.children()[i].parentIds.push(rootNode.children()[i].parent.id())
setParents(rootNode.children()[i]);
}
}

setParents(root);

可以查看 here

关于javascript - knockout js,从 TreeView 中选择的项目中找到所有父节点id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23739820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com