1

我正在使用 vis.js,并且已经研究出如何获取所有当前选定节点的数组。

var TempNodes = network.getSelectedNodes();

我的问题是 getSelectedNodes() 数组以从最低到最高的数字顺序返回所有节点 id ...似乎没有办法告诉最后选择的节点 id 是什么或第一个选择的节点是什么身份证是。我只能告诉选择了哪些节点 ID。

有谁知道一种方法可以从 getSelectedNodes 数组中找出第一个或最后一个选择的节点 id 是什么?

4

2 回答 2

1

文档特别指出getSelection()

返回一个包含所选节点 ID 的数组。如果没有选择节点,则返回一个空数组。选择没有排序。

由于目前选择多个节点的方式是长按,你可以自己保持选择顺序,通过监听选择事件:

var mySelectionOrder = [];
var previouslySelected = {};
network.on('select', function(p) {
      var selected = {};
      // add newly-selected nodes at end of mySelectionOrder
      p.nodes.forEach(function(n) {
            if ( ! previouslySelected[n]) { mySelectionOrder.push(n); }
            selected[n] = true;
      });
      // remove newly-unselected entries from mySelectionOrder
      mySelectionOrder = mySelectionOrder.filter(
            function(e, i, a) { return selected[e]; });
      // prepare for next run
      previouslySelected = selected;
      // output to console to make sure it works
      console.log("Selection updated", mySelectionOrder);
}); 

(已编辑以修复 JS 代码;经测试可与此示例一起使用)

于 2015-04-08T07:39:23.843 回答
1

使用 tucuxi 提出的概念,我确实想出了一些工作代码来实现这一点。尽管 tucuxi 的代码没有“直接开箱即用”,但他的想法是合理的,他值得称赞。

这是最终对我有用的代码

 var PreviouslySelectedNodes = [];
    var SelectedNodesInOrder = [];

    network.on('select', function (properties) {      

      // itterate through each visjs selected nodes and see if any value is not present in our current ordered list
      // If it's not already present, push it to the top of our ordered list
      var SelectedNodeIDs = network.getSelection().nodes // First get all the visjs selected nodes

      // If only one Node is currently selected, then empty the SelectedNodesInOrder array ready for a new set
      if(SelectedNodeIDs.length == 1){
          SelectedNodesInOrder = [];
      }

      // Cycle through all current selected visjs nodes
      for(var t = 0; t <= SelectedNodeIDs.length; t++){

          // cycle through all currently selected ordered nodes in our ordered array
          var found = false; flag the default as this node not already in our ordered list
          for(var y = 0; y <= SelectedNodesInOrder.length; y++){
                if(SelectedNodesInOrder[y] == SelectedNodeIDs[t]){ // This node already exists in our ordered list
                    found = true;
                }         
          }

          // If the current visjs selected node doesn't already exist in the SelectedNodesInOrder, then add it
          if(found === false){
                SelectedNodesInOrder.push(SelectedNodeIDs[t]);
          }

      }

    console.log(SelectedNodesInOrder); // test by dumping our ordered array list to the console

    });
于 2015-04-10T02:51:19.647 回答