我有一个用于显示时间表的库。根据您提供给库的数据,如果数据包含特定值,我想要显示元素。
没有number
值的示例:
var labelColorTestData = [
{label: "person a", times: [{"color":"green", "label":"Weeee", "starting_time": 1355752800000, "ending_time": 1355759900000}, {"color":"blue", "label":"Weeee", "starting_time": 1355767900000, "ending_time": 1355774400000}]},
{label: "person b", times: [{"color":"pink", "label":"Weeee", "starting_time": 1355759910000, "ending_time": 1355761900000}, ]},
{label: "person c", times: [{"color":"yellow", "label":"Weeee", "starting_time": 1355761910000, "ending_time": 1355763910000}]}
];
number
值的示例:
var testData = [
{times:[
{"id": "day1", "label": "DAY", "number": "1", "starting_time": 1, "ending_time": 86400},
{"id": "day2", "label": "DAY", "number": "2", "starting_time": 86400, "ending_time": 86400*2},
{"id": "day3", "label": "DAY", "number": "3", "starting_time": 86400*2, "ending_time": 86400*3},
{"id": "day4", "label": "DAY", "number": "4", "starting_time": 86400*3, "ending_time": 86400*4},
{"id": "day5", "label": "DAY", "number": "5", "starting_time": 86400*4, "ending_time": 86400*5}
]},
];
如果number
变量存在,我想添加一个文本元素。以下代码始终添加文本元素。
g.selectAll("svg").data(data).enter()
.append("text")
.attr("class", "textnumbers")
.attr("id", (d) => (d.id))
.attr("x", (d, i) => getXTextPos(d, i, d.number, '.textnumbers'))
.attr("y", getStackTextPosition)
.text(function(d) {
return d.number;
})
.on("click", function(d, i){
// when clicking on the label, call the click for the rectangle with the same id
var point = d3.mouse(this);
var id = this.id;
var selectedLabel = d3.select(this).node();
var selector = "rect#" + id;
var selectedRect = d3.select(selector).node();
click(d, index, datum, selectedLabel, selectedRect, xScale.invert(point[0]));
})
;
如果起始数据中存在number
,如果不存在,则如何添加文本元素?
谢谢!
答案 0 :(得分:2)
data(data).enter()
粘贴此行后
.filter(function(d) { return d.number !== undefined; })