简体   繁体   中英

Running a function for each element

I am using the Peity js plugin to create donut charts on my page. I am trying to animate the chart for each of the .foo elements:

<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();
});

However it won't work for some reason with no errors in console. If I remove the $('.foo').each(function () { ... } part (and all "this" instances) the code will work. Thanks in advance for any help.

When the timeout callback is executed, the this context refer to window, because you are actually calling window.setTimeout method.

Try this:

$('.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();
});

The problem is the context inside the timer handler, the easiest fix here is to use a closure variable

$('.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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM