如何删除父节点而不删除子节点

时间:2021-02-06 08:11:05

标签: cytoscape.js cytoscape cytoscape-web

这是我在 reactjs 中使用的代码示例。

const node = graph.$(`#${selectedNode.id()}`);
      graph.remove(node);

selectedNode.id 是父节点的 id,但它会删除此父节点内的所有子节点。 如何仅删除父节点而不删除其后代?

此问题与此处 Remove/hide compound node without removing/hiding descendants 上的问题类似,但如果提供了一些代码示例,我将不胜感激,因为在此处的文档中 http://js.cytoscape.org/#collection/graph-manipulation/eles.move 我们有一个浅层的边代码示例,但我对节点。

谢谢

1 个答案:

答案 0 :(得分:3)

您可以通过首先将其子节点移动到父节点的父节点(如果存在,否则应分配空值)然后删除父节点来删除父节点。在下面的例子中选择一个父节点并点击删除按钮。

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  layout: {name: 'grid', rows: 2},
  style: [{
      selector: 'node',
      css: {
        'label': 'data(id)'     
        }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'n0',
          parent: 'n1'
        }
      },
      {
        data: {
          id: 'n1',
          parent: 'n2'
        }
      },
      {
        data: {
          id: 'n2'
        }
      },
      {
        data: {
          id: 'n3'
        }
      }
    ],
    edges: [
      {
        data: {
          id: 'n2n3',        
          source: 'n2',
          target: 'n3',
          weight: 7
        }
      }
    ]
  }
});

document.getElementById("deleteButton").addEventListener("click", function() {
  let selected = cy.nodes(':selected')[0];
  selected.children().move({parent : (selected.parent().id() ? selected.parent().id() : null)});
  selected.remove();
});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#button {
  z-index = 1000;
}

#cy {
  height: 95%;
  width: 95%;
  left: 0;
  top: 50;
  z-index = 900;
  position: absolute;
}
<html>

<head>
  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
  <script src="https://unpkg.com/cytoscape@3.10.0/dist/cytoscape.min.js">
  </script>
</head>

<body>
  <button id="deleteButton" type="button">Delete selected</button>
  <div id="cy"></div>
</body>

</html>

相关问题