jQuery每个都有SetTimeout

时间:2011-12-23 10:18:16

标签: javascript jquery google-maps-api-3

有谁能告诉我为什么这不起作用?

jeMarkers是一系列Google地图标记。

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 个答案:

答案 0 :(得分:2)

您必须在函数内缓存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++;
    });
}