在新窗口上使用d3.js [英] Use d3.js on a new window
问题描述
打开新窗口时是否可以使用d3.js?例如,我正在尝试:
Is it possible to use d3.js when opening new windows? For example, I am trying:
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的输出是
It doesn't work and the ouput of the first console.log is
[
Array[1]
0: null
length: 1
parentNode: HTMLHtmlElement
__proto__: Array[0]
]
我认为0: null
不好.
推荐答案
这里有一些问题:
-
我认为您没有正确打开新窗口-通常,您打开的是包含内容的URL,或者您使用
""
作为URL并将内容写入空白窗口.打开类似"usertable.html"
的URL,然后编写<html><body>
没有任何意义.最后,即使窗口空白,也无需编写<html><body>
-浏览器通常会默认提供这些节点.
I think you're opening the new window incorrectly - generally, you either open a URL with content, or you use
""
as the URL and write your content into a blank window. Opening a URL like"usertable.html"
and then writing<html><body>
doesn't make sense. Finally, even with a blank window, you don't need to write<html><body>
- the browser will generally provide these nodes by default.
默认情况下,使用d3.select
会在当前文档中显示.为了访问新打开的窗口的主体,您需要传递new_window.document
-实际上,您需要传递new_window.document.body
,因为如果没有HIERARCHY_REQUEST_ERROR
.
Using d3.select
is going to look, by default, in the current document. In order to access the body of the newly opened window, you'll need to pass in new_window.document
- in fact, you'll need to pass in new_window.document.body
, since you can't append anything to document
without a HIERARCHY_REQUEST_ERROR
.
我也不认为将D3与document.write
混合是一个好主意. D3选择DOM中的节点,并且您现在有了代码,在您尝试选择table
之前,我不认为您的table
实际上是格式良好的节点. D3非常擅长插入新的DOM节点-请改用它.
I also don't think it's a good idea to mix D3 with document.write
as you're doing here. D3 selects nodes in the DOM, and the way you have the code now, I don't think your table
is actually a well-formed node until after you've tried to select it. D3 is perfectly good at inserting new DOM nodes - use it instead.
将所有这些放在一起会得到如下结果:
Putting all this together yields something like this:
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/
这篇关于在新窗口上使用d3.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!