jQuery каждый с SetTimeout - PullRequest
       1

jQuery каждый с SetTimeout

0 голосов
/ 23 декабря 2011

Может кто-нибудь сказать мне, почему это не работает?

jeMarkers - это массив маркеров Google Maps.

function toggleBounce() {
    var bcounter = 0;
    $(jeMarkers).each(function () {
        setTimeout(function () {
            if (this.getAnimation() != null) {
                this.setAnimation(null);
            } else {
                this.setAnimation(google.maps.Animation.BOUNCE);
            }
        }, bcounter * 100);
        bcounter++;
    });
}

Если я делаю то же самое без функции setTimeout, она работает, ноочевидно делает все маркеры сразу:

function toggleBounce() {
    $.each(jeMarkers, function () {
        if (this.getAnimation() != null) {
            this.setAnimation(null);
        } else {
            this.setAnimation(google.maps.Animation.BOUNCE);
        }
    });

1 Ответ

2 голосов
/ 23 декабря 2011

Вам необходимо кэшировать объект this внутри функции, поскольку контекст setTimeout не устанавливается автоматически:

function toggleBounce() {
    var bcounter = 0;
    $(jeMarkers).each(function () {
        var that = this; // <- Cache the item
        setTimeout(function () {
            if (that.getAnimation() != null) {
                that.setAnimation(null); // <- Now we can call stuff on the item
            } else {
                that.setAnimation(google.maps.Animation.BOUNCE);
            }
        }, bcounter * 100);
        bcounter++;
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...