javascript - 在新窗口中使用 d3.js

标签 javascript d3.js html-table console window

是否可以在打开新窗口时使用 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; });

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

关于javascript - 在新窗口中使用 d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12369823/

相关文章:

javascript - D3.js:生成 X 轴会删除我的一些点的标签,生成 Y 轴会将它们全部删除

javascript - D3 中带圆圈的两行

JavaScript 使用 (this) 关键字

javascript - 为什么flow在使用instanceof时会给出uncovered code warning?

javascript - jQuery UI 模态对话框在 JSP 上立即关闭

javascript - D3 隐藏图表区域的溢出,当Y轴有最小值和最大值时

javascript - 如何在不通过 AJAX 加载数据的情况下使用 JavaScript 对 HTML 表格进行排序?

Jquery 淡入淡出背景/表格行上的动画背景颜色

javascript - onClick 方法中的 React setState 不更新 DOM

javascript - Mongoose 处理 promise 调用和 Express 中间件中的验证错误