是否可以在打开新窗口时使用 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
不好。
最佳答案
这里有几个问题:
我认为您打开新窗口的方式不正确 - 通常,您要么打开包含内容的 URL,要么使用
""
作为 URL 并将您的内容写入空白窗口。打开类似"usertable.html"
的 URL然后写<html><body>
没有意义。最后,即使有一个空白窗口,你也不需要写<html><body>
- 浏览器一般会默认提供这些节点。使用
d3.select
默认情况下,将在当前文档中查找。为了访问新打开的窗口的主体,您需要传入new_window.document
- 实际上,您需要传入new_window.document.body
,因为您不能将任何内容附加到document
没有HIERARCHY_REQUEST_ERROR
.我也不认为将 D3 与
document.write
混合使用是个好主意。正如你在这里所做的那样。 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; });
关于javascript - 在新窗口中使用 d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12369823/