1

打开新窗口时是否可以使用 d3.js?例如,我正在尝试:

new_window = window.open("userpage.html");
new_window.document.write("<html><body>");
new_window.document.write("<table id=\"usertable\">");
new_window.document.write("</table>");
new_window.document.write("</body></html>");    
table = d3.select("#usertable");
console.log(table);
var thead = table.append("thead");
var tbody = table.append("tbody");
var columns = ["dataset"];

thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
    .text(function(column) { console.log(column); return column; });

它不起作用,第一个 console.log 的输出是

[
Array[1]
0: null
length: 1
parentNode: HTMLHtmlElement
__proto__: Array[0]
]

我觉得0: null不好。

4

1 回答 1

7

这里有几个问题:

  • 我认为您打开新窗口不正确-通常,您要么打开带有内容的 URL,要么将""其用作 URL 并将内容写入空白窗口。打开一个类似的 URL"usertable.html"然后写<html><body>是没有意义的。最后,即使是空白窗口,您也无需编写<html><body>- 浏览器通常会默认提供这些节点。

  • d3.select默认情况下,使用将在当前文档中查找。为了访问新打开的窗口的主体,您需要传入new_window.document- 事实上,您需要传入new_window.document.body,因为没有 . 就无法附加任何document内容HIERARCHY_REQUEST_ERROR

  • 我也不认为document.write像你在这里做的那样混合 D3 是一个好主意。D3 选择 DOM 中的节点,而您现在拥有代码的方式,我不认为您table实际上是一个格式良好的节点,直到您尝试选择它之后。D3 非常擅长插入新的 DOM 节点——使用它来代替。

将所有这些放在一起会产生如下结果:

var newWindow = window.open('');

var newWindowRoot = d3.select(newWindow.document.body);

// now do some writing with D3
var data = [
    { foo: "Foo 1", bar: "Bar 1" },
    { foo: "Foo 2", bar: "Bar 2" }
];

var table = newWindowRoot.append('table');

var rows = table.selectAll('tr')
    .data(data);

rows.enter().append('tr');

var cells = rows.selectAll('td')
    .data(function(d) { return d3.entries(d); });

cells.enter().append('td');

cells.text(function(d) { return d.value; });

工作示例:http: //jsfiddle.net/nrabinowitz/gQf7J/

于 2012-09-11T21:07:38.937 回答