gpt4 book ai didi

javascript - jQuery 各有 SetTimeout

转载 作者:行者123 更新时间:2023-12-02 19:56:10 31 4
gpt4 key购买 nike

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

jeMarkers 是 Google map 标记的数组。

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

最佳答案

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

关于javascript - jQuery 各有 SetTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614842/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com