无法读取属性undefined

问题描述:

前端开发不是我的强大套件,我坚持我觉得可能很明显的东西。无法读取属性undefined

我试图从一个JSON文件,其中工程加载一组节点,但是当我从另一个JSON文件添加新节点,它抛出这个错误:

Uncaught TypeError: Cannot read property 'apply' of undefined 
at updateStyle (cytoscape.min.js:27) 
at a.c.restore (cytoscape.min.js:27) 
at a (cytoscape.min.js:27) 
at u.add (cytoscape.min.js:27) 
at HTMLDocument.<anonymous> (?q=:42) 
at j (jquery-3.2.1.min.js:2) 
at k (jquery-3.2.1.min.js:2) 

是它的一些有点冲突?错误的代码?

HTML:

<html> 
<head> 
    <script 
      src="http://code.jquery.com/jquery-3.2.1.min.js" 
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
      crossorigin="anonymous"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.1.4/cytoscape.min.js"></script> 
    <style> 
     body { 
      width: 100%; 
      height: 100%; 
     } 
     #cy { 
      width: 100%; 
      height: 100%; 
      display: block; 
     } 
    </style> 
    <script> 
     $(document).ready(function() { 

      var data = $.getJSON('example.json'); 
      var data2 = $.getJSON('example2.json'); 

      var cy = window.cy = cytoscape({ 
       container: document.getElementById('cy'), 
       elements: data, 

       style: [{ 
        // This is now essentially your default for the graph 
        selector: 'node', 
        style: { 
         'background-color': '#666', 
         'label': 'data(id)' 
        } 
       }], 
       layout: { 
        name: 'grid' 
       } 
      }); 

      cy.add({ 
       data: data2 
      }); 
     }); 
    </script> 
</head> 
<body> 
<div id="cy"></div> 
</body> 

example.json:

[ 
{ 
    "data": { "id": "a" } 
}, 
{ 
    "data": { "id": "b" } 
}, 
{ 
    "data": { "id": "ab", "source": "a", "target": "b" } 
} 
] 

example2.json:

[ 
{ 
    "data": { "id": "c" } 
}, 
{ 
    "data": { "id": "d" } 
}, 
{ 
    "data": { "id": "ac", "source": "a", "target": "c" } 
} 
] 
+1

我敢打赌'data'和'data2'不包含你认为他们做的事。 http://api.jquery.com/jQuery.getJSON –

+0

^它们包含Deferred对象/ jqXHR对象,可能不是你想要的对象 – adeneo

为方便起见,Cytoscape中,您可以用thennable界面中指定的承诺(什么)初始化元素和样式。无论如何,Init可以是异步的,因为一些布局是异步的。

图表操作不会允许您传递承诺。这将使所有的基本操作异步,这会使事情变得复杂的用户。

如果你不熟悉的承诺,看看在MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

例如promise.then(resolvedValue => doSomethingWith(resolvedValue));