我试图描绘美国历史上过去30年的所有重大事件。这是代码片段 -
var mevent = svg.append("text")
.attr("class", "year event")
.attr("text-anchor", "end")
.attr("y", height - 450)
.attr("x", width - 300)
.text("mevent");
var mevents =
{"1987":[""],
"1988":["Pan Am Flight 103", "US President Election"],
"1989":["Cyclone in NE", "Bay Area Earth Quake"],
"1990":["Tornado in MW", "Gulf War 1"],
"1991":["Rodney King LA"],
"1992":["Cyclone in SE", "US President Election"],
"1993":["Great Flood of 1993 in MidWest", "Blizzard in NorthEast"],
"1994":["Earthquake in LA"],
"1995":["Flood in SouthEast", "Heat Wave in MidWest", "OJ Simpson Trial"],
"1996":["Summer Olympics in Atlanta", "US President Election"],
"1997":["Flood in MidWest", "Death of Princess Diana"],
"1998":["Blizzard Ice Storm in NorthEast"],
"1999":["Landslide in WA", "66 Tornadoes across MidWest and South", "Heat Wave in MidWest and NorthEast"],
"2000":["Dot com bubble burst", "US President Election and Florida Recount"],
"2001":["Cyclone in South", "9/11"],
"2002":["US Invasion of Afganistan", "Winter Olympics in Salt Lake City, Utha", "US Airways Bankruptcy", "United Airlines Bankruptcy"],
"2003":["Gulf War 2", "United Airlines Bankruptcy"],
"2004":["Cyclones across TX, FL and East Coast", "US President Election", "Asia Tsunami"],
"2005":["7 Tornadoes across MidWest, South and SouthEast", "Death of Pope John Paul 2", "Hurrican Katrina"],
"2006":["United Airlines comes out of Bankruptcy"],
"2007":["Wildfires in CA"],
"2008":["Tornados across South", "Lehman Brothers", "US President Election", "Mumbai Terror Attacks"]};
console.log(mevents[year]);
event.text(typeof mevents[year] + " " + mevents[year]);
我可以在控制台中打印这些值。但我无法将它们分配给文本变量。我错过了什么?
答案 0 :(得分:0)
假设svg
只包含一个节点,实际上只是附加一个text
元素(字符串值为“mevent”)。
听起来你想要的是进行数据连接,这将导致数据数组中每个元素的text
节点。
var mevent = svg.selectAll("text")
.data(mevents)
.enter().append("text")
.attr("class", "year event")
.attr("text-anchor", "end")
.attr("y", height - 450)
.attr("x", width - 300)
.text("mevent");
通过阅读Thinking With Joins教程,您可以了解更多相关信息。这是使用d3的一个非常基本的部分,因此值得投入一些时间来真正了解它是如何工作的。