簡體   English   中英

tree-model-js如何獲取先前的節點ID

[英]tree-model-js how to get previous node id

我想從樹中知道先前訪問的節點。 嘗試下面的例子

var TreeModel = require('tree-model');
tree = new TreeModel();

rootMain = tree.parse({
    id: 1,
    children: [
        {
            id: "11",
            children: [{id: "111"}]
        },
        {
            id: "12",
            children: [{id: "121"}, {id: "122"}]
        },
        {
            id: "13"
        }
    ]
});

如果假設我遍歷節點121和122我想要父節點,那么它應該返回我12如果假設我遍歷節點111我想要父節點,那么它應該返回我11如果假設我遍歷節點13我想要父節點,那么它應該返回1

在遍歷樹時,您可以使用node.parent獲得當前節點的父級。

rootMain.walk(node => {
  console.log('node id:', node.model.id);

  if(node.parent) {
    console.log('parent node id:', node.parent.model.id);
  }
});

這將記錄所需的父ID

var parent_id;

rootMain.walk(function (node) {

    var current_id = node.model.id;
    if (node.model.id === 121) 
        console.log(parent_id);
        return true;
    parent_id = current_id;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM