如何执行饼图一旦模态被单击

How to execute pie chart once modal is clicked

本文关键字:模态 单击 何执行 执行      更新时间:2023-09-26

我有一个页面上的链接,我想打开并显示一个饼状图。然而,Javascript会立即执行,因此不会出现在Modal表单中。有办法改变吗?

链接到modal:

 <a href="#graphModal" data-target="#graphModal" data-toggle="modal" class="glyphicon glyphicon-stats" id="altChartButton" onclick="pieFunction()"></a>

脚本:

<script id="pieCode">
        var width = 960,
           height = 500,
           radius = Math.min(width, height) / 2;
        var color = d3.scale.ordinal()
            .range(["#6ec393", "#9b80bb", "#e54a24"]);
        var arc = d3.svg.arc()
            .outerRadius(radius - 10)
            .innerRadius(0);
        var pie = d3.layout.pie()
            .sort(null)
            .value(function (d) { return d.Value.Value; });
        var svg = d3.select("#pieData").append("svg")
            .attr("width", width)
            .attr("height", height)
          .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
        var data = @Html.Raw(@Model.output);
        var g = svg.selectAll(".arc")
            .data(pie(data))
          .enter().append("g")
            .attr("class", "arc");
        g.append("path")
            .attr("d", arc)
            .style("fill", function (d) { return color(d.data.Category.Category); });
        g.append("text")
            .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .style("font-weight", "bold")
            .style("font-size", "15px")
            .style("font-family", "'futura-pt-n7', 'futura-pt', 'Helvetica', 'Arial', 'sans-serif'")
            .text(function (d) { return d.data.Category.Category; });
    </script>
模态:

 <div id="graphModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 style="text-align:center">Pie chart for: @Model.ReportDescription</h1>
                    </div>
                    <div class="modal-body" id="pieChart">
                       <div id="pieData"></div>
                    </div>
                </div>
            </div>
        </div>

我不确定您使用的是哪些库或框架,但在您提供的任何代码中都没有定义pieFunction。

在不了解更多信息的情况下,最简单的解决方案可能是将脚本标记中的代码包装在名为pieFunction 的函数中。
function pieFunction(){
    //place code inside your script tag here...
}

但是,如果您希望代码在打开modal后执行,则可能需要在回调中执行该函数。如果你能发布更多的细节,我也许能帮助更多。使用bootstrap,您可以删除onclick="pieFunction()",并在document ready上添加以下内容:

$('#graphModal').on('show.bs.modal', function (event) {
    pieFunction();
});