[英]Running a function for each element
我正在使用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”實例),代碼將起作用,在此先感謝您的幫助。
當執行超時回調時, this
上下文引用window,因為您實際上正在調用window.setTimeout
方法。
嘗試這個:
$('.foo').each(function () {
var updateChart = $(this).peity('donut');
var text = "";
var i = 0;
function myLoop() {
setTimeout($.proxy(function () {
text = i + "/12";
updateChart.text(text)
.change()
i = i + 0.2;
var maxValue = $(this).data("value");
if (i <= maxValue) myLoop();
},this), 0.5)
}
myLoop();
});
問題是計時器處理程序中的上下文,這里最簡單的解決方法是使用閉包變量
$('.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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.