未捕获的TypeError:无法读取null的属性'classList'-SVG

时间:2018-08-29 21:08:27

标签: javascript html svg

我有一个交互式SVG映射,其中包含很多区域,我正在使用websockets将区域数据从Node.js服务器发送到clinet。但是当我进入代码的一部分时,控制台会显示一条错误消息Uncaught TypeError: Cannot read property 'classList' of null

Javascript:

socket.on('mapData', function(data) {
    for (let i = 0; i < data.length; i++) {   // data is an array of objects, its length is 41, while all areas i have on the svg are 49
        let area = document.getElementById("map").getSVGDocument().getElementById('area_'+i);
        if (data[i].owner == "client") {
            area.classList.add('y');
            area.classList.remove('st0');
            area.id = "home";
        } else {
            if (data[i].owner == null) {
                area.setAttribute("fill", "#ffffff");
                area.id = "unallocated_"+i;
            } else {
                // everything above works great, the error starts from here
                area.classList.add('t');
                area.id = data[i].owner;
            }
        }
    }
});

SVG地图的一部分:

<g id="ThirdProvince">
<path id="area_3" class="st0" d="M147.4,68l-2.1,2.3l0.3,1l0.1,0l0.2,0.1l0.1,0l0.6,0.1l0.2,0l0.2,0.1l0.1,0.1l0.1,0.1l0.1,0.2
    l0.1,0.2l0,0.3l0,0.3l0,0.2l-0.1,0l-1,0.2l-1,0l-0.8-0.1l-0.2,0l-0.4-0.1l-0.8-0.2l-0.1,0l-0.3,0l-0.2,0l-0.3,0.1l-0.7,0.4l-0.1,0
    l0,0.1l0.1,0.4l-0.3,0l-1.1-0.1l-1.2-0.3l-0.1-0.1l-0.1-0.1l0-0.4l0-0.1l-0.1-0.3l-0.1-0.1l-0.1,0l-0.3-0.1l-3.9-1l-0.2,0l-1.6-0.2
    l-1.3-0.2l-2.5-0.3l-0.8,0.4l-0.4,0.2l-0.4,0.2l-0.1,0l-0.3,0l-1.1,0l-0.5,0.2l-0.1,0l-0.2-0.1l-0.1,0l0-0.1l0.1-2l0-0.3l0.5-1.1
    l0.6-1l0.1,0l0.5-0.1l0.2,0l0.2,0.1l0.2,0l1.1-0.3l0.1-0.1l0-0.1l0-0.1l-2.1-1.3l-0.4,0.1l-1.3,0.1l-0.2,0l-0.5-0.1l-0.8-0.2
    l-0.4-0.1l-0.3,0l-0.1,0l0,0l-0.4-1.4l0,0l0.1-0.2l0.4-0.2L126,62l0.4-0.5l0.1-0.2l0.3-0.2l0.8-0.4l0.8-0.1l0.4,0l0.2,0.1l0.1,0.1
    l0,0l0.1,0.1l0.1,0l1.8-0.1L134,60l0.9-0.3l0.1,0l1-1.3l0.9-0.7l0.4,0.3l1.1,1.1l0.4,0.5l1.1,1l0.1,0.1l0.3,0.1l1.5,0l1.2,0
    l0.4,0.2l0.7,0.4l0.1,0.1l0.1,0.1l0.4,0.6l-0.1,0.4l-0.1,0.8l1.5,1.2l0.8,0.2l0.6,0.1l0.2,0l1-0.2l0.5,0.1l0.8,1.1l0.1,0.1l0,0.1
    l-0.1,0l-0.5,0.2l-0.6,0.1l-0.2,0l-0.1,0.1l-0.1,0.1l-0.3,0.7L147.4,68z"/>
</g>

CSS类:

.st0{stroke:#000000;cursor:pointer;}
.st0:hover {fill: #fce57e;}
.t {fill:#47a3e5;stroke:#000000;cursor:pointer;}
.t:hover {fill: #fce57e;}
.y {fill:#2bd88d;stroke:#000000;}

服务器发送的部分数据:

data = [{id:0,owner=null},{id:1,owner="other"},{id:2,owner="other"},{id:3,owner=null},{id:4,owner="client"},{id:5,owner=null}, ... ,{id:40,owner=null}];

我不太明白为什么会显示错误。

1 个答案:

答案 0 :(得分:0)

据我所知,您的问题是您的程序找不到ID为area_1的元素,因为您说console.log(i)仅输出1。这是因为您可以找不到那个元素。另外,在您提到的控制台错误中,它是在哪行上指出了错误发生的原因?