【问题标题】:Passing D3 data to bootstrap modal dialog将 D3 数据传递给引导模式对话框
【发布时间】:2017-09-19 18:59:08
【问题描述】:

我正在使用 D3 创建许多图表,每个图表都包含在引导选项卡元素中。我为包含 D3.csv 导入数据集元素的图表元素创建数据丰富的鼠标悬停/工具提示没有问题。但是,当我创建一个在用户单击图表元素时启动的引导模式对话框时,我得到了该对话框,但无法将 D3 数据传递给它。基本模式对话框如下所示:

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

在 javascript 中使用

// open modal dialogue on click
$('#myModal').on('show.bs.modal', function(d) {
    let modalTitle = d3.selectAll("h4.modal-title");
    modalTitle.text("test");
    let modalBody = d3.selectAll(".modal-body");
    modalBody.html("Country should be: " + d.Country + "<br>" + "Operator should be: " + d.Operator);
    console.log("operator: " + d.Operator + "   Country: " + d.Country);
})

我可以将文本推送到模态对话的元素中,但我无法访问 csv 值数组,例如d.Country, d.Operator 我可以用鼠标悬停。我怀疑这是因为我没有使用d3.selectAll 来选择对话的#myModal ID,但我似乎无法通过任何形式的d3.selectAll 语句识别show.bs.modal。我是否必须像 this problem 中那样通过 div 中的数据 ID 分配将所有数据传递给模态?我已经尝试过,但是当 bootstrap 附加到 SVG 元素而不是 HTML 元素时,它似乎没有获取数据。

这是问题的Plunker

【问题讨论】:

    标签: twitter-bootstrap d3.js bootstrap-modal


    【解决方案1】:

    你可以这样做:

    第一步

    在您的鼠标悬停功能中,添加数据和一个类以供选择。

        h.append("rect")
            .style("stroke", "black")
            .style("stroke-width", "4")
            .style("fill", "none")
            .style("stroke-linecap", "round")
            .style("stroke-linejoin", "round")
            .attr("class", "infoLine info")<---add class info
            .datum(d)<---add datum to the rect.
    

    第二步

    在你的点击函数中,使用info类获取数据。

    $('#myModal').on('show.bs.modal', function(d) {
        var d = d3.select(".info").data().pop(); <--- get the data from group having class info
        let modalTitle = d3.selectAll("h4.modal-title");
        modalTitle.text("test");
        let modalBody = d3.selectAll(".modal-body");
        modalBody.html("Country should be: " + d.Country + "<br>" + "Operator should be: " + d.Operator);
        console.log(d, "operator: " + d.Operator + "   Country: " + d.Country);
    })
    

    工作代码here

    【讨论】:

    • 太棒了。像魅力一样工作。我永远不会解决这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 2013-07-06
    • 2016-01-22
    • 1970-01-01
    • 2017-12-31
    • 2017-08-23
    • 2014-11-13
    相关资源
    最近更新 更多