在按钮上单击打开一个新的 window 并用 D3 画一个圆

On button click open a new window and draw a circle with D3

我正在尝试打开一个新的 window 单击按钮并在其上绘制一个简单的圆圈。

我可以打开 window,但使用此代码不会出现圆圈。关于如何解决这个问题的任何想法。0

这是我的代码:

function drawBarChart(newWindowRoot){
    var sampleSVG = d3.select(newWindowRoot)
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

    sampleSVG.append("circle")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("r", 40)
        .attr("cx", 50)
        .attr("cy", 50)
        .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
        .on("mouseout", function(){d3.select(this).style("fill", "white");});
}
function createNewPage(){

    var button = content.append("button")
            .attr("class", "button")
            .attr("id", "myButton")
            .text("Visualize");

    document.getElementById("myButton").onclick = function () {

        var newWindow = window.open('');
        newWindowRoot = d3.select(newWindow.document.body)
            .attr("width","1060px")
            .attr("margin","50px auto");

        drawBarChart(newWindowRoot);

    }

}

当您调用 drawBarChart(newWindowRoot) 时,您将 d3 选择(d3.select(newWindow.document.body) 的结果)传递给该函数。有道理。

但是,从 drawBarChart 中调用 var sampleSVG = d3.select(newWindowRoot),本质上是对 d3 选择进行 d3 选择。这行不通(与您对 jQuery 的期望不同)。您应该跳过后者 d3.select ,这将使您的代码开始工作。更具体地说,这将使按钮出现在新 window 中,但不会出现在圆圈中。

要显示圆圈,您需要解决另一个问题:您的 fiddle 尝试将圆圈添加到按钮,而不是 SVG(这与上面的示例不同,后者不是试图创建一个按钮)。

Here's a working fiddle

顺便说一下,您 link 的 jsFiddle 不起作用的原因是因为您嵌入的 link 使用安全协议 (https) 和 jsfiddle试图加载 d3 的功能不安全 (http),这会导致加载 d3 失败,进而导致执行代码时出错。