如何在cytoscape.js中向节点的数据字段添加属性?

问题描述 投票:0回答:1

[我正在尝试使用“ parent”字段动态更新cy对象的节点。首次从json文件中加载元素时,它们没有父字段。文档说我应该能够简单地使用cy.data( name, value )设置特定的数据字段。 但是,这似乎只适用于属性名称已经存在的名称。

我曾考虑过为每个节点创建一个副本,以将我的父级属性添加到其中,然后删除旧节点;但是我的图表很大,这似乎是不得已的方法。

cytoscape.js cytoscape cytoscape-web
1个回答
0
投票

我用我的代码尝试过此操作,并使其与.data()一起正常工作:

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  style: [{
      selector: 'node',
      style: {
        'label': 'data(id)'
      }
    },
    {
      selector: 'edge',
      style: {
        'curve-style': 'bezier',
        'target-arrow-shape': 'triangle'
      }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'a'
        }
      },
      {
        data: {
          id: 'b'
        }
      },
      {
        data: {
          id: 'c'
        }
      },
      {
        data: {
          id: 'd',
          parent: 'p'
        }
      },
      {
        data: {
          id: 'p'
        }
      }
    ],
    edges: [

    ]
  }
});

cy.bind('click', 'node', function(evt) {
  var target = evt.target
  console.log(target.data())
  target.data('newAttribute', 1)
  console.log(target.data())
});
body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px;
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}
<head>
  <title>cytoscape-add-attribute demo</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
</head>

<body>
  <h1>cytoscape add-attribute-demo</h1>
  <div id="cy"></div>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.