我在循环($ .each)中收集参数后绘制了一个图表。字符串已组装,但不能那样工作
var PieData = company;
并且当我复制行并直接粘贴时,它可以正常工作。
var PieData = [{value: 14, color: '#2bea4f', highlight:'#2bea4f', label: 'Cts group'},{value: 4, color: '#411820', highlight:'#411820', label: 'СБЕРГРУЗ'},{value: 18, color: '#3b53a4', highlight:'#3b53a4', label: 'Фаворит Экспресс'},{value: 3, color: '#698bb4', highlight:'#698bb4', label: 'Бечехан'},];
如何使其工作?
下面的源代码
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $('#pieChart').get(0).getContext('2d')
var pieChart = new Chart(pieChartCanvas)
var company = "[";
$.each( obj, function( key, value ) {
var col = randColor();
company += "{value: " + value.countShip + ", color: '" + col + "', highlight:'" + col + "', label: '" + value.name + "'},";
});
company += "]";
//var PieData = company;
var PieData = [{value: 14, color: '#2bea4f', highlight:'#2bea4f', label: 'Cts group'},{value: 4, color: '#411820', highlight:'#411820', label: 'СБЕРГРУЗ'},{value: 18, color: '#3b53a4', highlight:'#3b53a4', label: 'Фаворит Экспресс'},{value: 3, color: '#698bb4', highlight:'#698bb4', label: 'Бечехан'},];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,
//String - The colour of each segment stroke
segmentStrokeColor : '#fff',
//Number - The width of each segment stroke
segmentStrokeWidth : 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect
animationEasing : 'easeOutBounce',
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,
//Boolean - whether to make the chart responsive to window resizing
responsive : true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio : true,
//String - A legend template
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
}
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
您的问题有点不清楚,尽管从对代码的简短了解中我发现您尝试将String用作JSON对象。
尝试替换
var PieData = company;
与
var PieData = JSON.parse(company);