D3键功能参数未定义 [英] D3 key function param undefined

查看:153
本文介绍了D3键功能参数未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据与元素绑定

首先,我选择我的元素

let trainSelect = svg.selectAll('.train-w-dir');

当我console.log(trainSelect)时,我得到的元素不是空的

When I console.log(trainSelect) I get elements not emty

然后我绑定数据

trainSelect
        .data(schedules, function(d: ISchedule) {
          return d.train;
        })
        .enter()
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide);

我在调试器上检查计划,该计划包含对象数组. 但是在键函数d id undefined中,我不知道为什么?

I check schedules on the debugger it contains array of objects. But inside the key function d id undefined I don't get why ?

所以我收到错误Cannot read property 'train' of undefined

推荐答案

对键函数的求值是两次:每个选择的元素一次,每个数据一次.用文档(强调我的名字):

The key function is evaluated twice: once per each element of the selection and once per each datum. In the words of the docs (emphasis mine):

对该键功能进行每个选定元素的评估,依次传递当前基准点(d),当前索引(i)和当前组(节点),其值为当前的DOM元素(节点 [ i ]);返回的字符串是元素的键.然后还对数据中的每个新数据进行评估,并向其传递当前数据(d),当前索引(i)和组的新数据,并将其作为组的父DOM.元素;返回的字符串是基准的键.

This key function is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]); the returned string is the element’s key. The key function is then also evaluated for each new datum in data, being passed the current datum (d), the current index (i), and the group’s new data, with this as the group’s parent DOM element; the returned string is the datum’s key.

在第一次运行时,如果尚未为每个元素绑定数据,则未定义d.

In the first run when evaluated for each selected element d will be undefined if you have not yet bound data to the elements.

您提供的代码尚不清楚,什么可能是解决问题的最佳方法.您可以提供安全保护措施以防止键函数中的未定义值,或者可能更好地重建将数据绑定到元素的方式.

It is not clear from the code you provided what might be the best solution to your problem. You could either provide a safe-guard against undefined values in the key function or, probably better, rebuild the way you bind data to your elements.

相关: 加入现有d3.js的DOM元素

这篇关于D3键功能参数未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆