0

我试图策划美国历史上过去 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]);

我可以在控制台中打印这些值。但我不能将它们分配给文本变量。我错过了什么?

4

1 回答 1

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 的一个非常基本的部分,因此值得花一些时间来真正了解它的工作原理。

于 2013-09-19T05:26:40.140 回答