我正在使用Peity js插件在页面上创建甜甜圈图。我正在尝试为每个.foo
元素设置图表动画:
<span class="foo" data-value="10"></span>
$('.foo').each(function () {
var updateChart = $(this).peity('donut');
var text = "";
var i = 0;
function myLoop() {
setTimeout(function () {
text = i + "/12";
updateChart.text(text)
.change()
i = i + 0.2;
var maxValue = $(this).data("value");
if (i <= maxValue) myLoop();
}, 0.5)
}
myLoop();
});
但是由于某种原因,它将无法正常运行,并且控制台中没有错误。如果删除
$('.foo').each(function () { ... }
部分(以及所有“ this”实例),该代码将起作用。在此先感谢您的帮助。 最佳答案
问题是计时器处理程序中的上下文,这里最简单的解决方法是使用闭包变量
$('.foo').each(function () {
var $this = $(this);
var updateChart = $this.peity('donut');
var text = "";
var i = 0;
function myLoop() {
setTimeout(function () {
text = i + "/12";
updateChart.text(text)
.change()
i = i + 0.2;
var maxValue = $this.data("value");
if (i <= maxValue) myLoop();
}, 0.5)
}
myLoop();
});