我目前有一个for循环,我正在其中运行一个脚本。
每当循环运行和执行函数时我都会记录。
这是我的代码示例:
此脚本处于循环中,运行3次
<script>
console.log ("LOOP");
var impressions = [<?= implode(",", $prod_impression_dots) ?>];
var testdata = [
{
"key" : "Impressions" ,
"type": "line",
"values" : impressions,
"yAxis": 1
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
nv.addGraph(function() {
console.log ("Add graph is called here");
console.log (testdata);
var chart = nv.models.multiChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d,i) { return i })
.color(d3.scale.category10().range());
chart.xAxis
.tickFormat(function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
if (typeof (dx) == undefined || d > 1000) {
dx = new Date (d);
}
else {
dx = new Date (dx);
}
return dx ? d3.time.format('%x')(dx) : '';
});
chart.yAxis1
.tickFormat(d3.format(',.1f'));
chart.yAxis2
.tickFormat(d3.format(',.4f'));
d3.select('#chart<?= $counter ?> svg')
.datum(testdata)
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
</script>
脚本下方是div标签
<div id='chart<?= $counter ?>' style="width:1150px;height:300px;font-size:11px;margin-top:5px">
<svg> </svg>
</div>
运行之后。控制台日志中的输出如下;
LOOP
LOOP
LOOP
Add graph is called here
[Object, Object, Object, Object]
Add graph is called here
[Object, Object, Object, Object]
Add graph is called here
[Object, Object, Object, Object]
total 199 nv.d3.js:40
我只是想知道为什么在循环的一次迭代之后没有执行该函数。这会导致所有图形具有相同的数据。
感谢。
答案 0 :(得分:0)
你的addGraph完整函数绝对是异步调用的。你可以像这样解决这个问题。
<script>
console.log ("LOOP");
var impressions = [<?= implode(",", $prod_impression_dots) ?>];
var testdata = [
{
"key" : "Impressions" ,
"type": "line",
"values" : impressions,
"yAxis": 1
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
nv.addGraph((function (testdata) {
return function() {
console.log ("Add graph is called here");
console.log (testdata);
var chart = nv.models.multiChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d,i) { return i })
.color(d3.scale.category10().range());
chart.xAxis
.tickFormat(function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
if (typeof (dx) == undefined || d > 1000) {
dx = new Date (d);
}
else {
dx = new Date (dx);
}
return dx ? d3.time.format('%x')(dx) : '';
});
chart.yAxis1
.tickFormat(d3.format(',.1f'));
chart.yAxis2
.tickFormat(d3.format(',.4f'));
d3.select('#chart<?= $counter ?> svg')
.datum(testdata)
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
}
})(testdata));
</script>