Javascript jQuery每个都带有SetTimeout

Javascript jQuery每个都带有SetTimeout,javascript,jquery,google-maps-api-3,Javascript,Jquery,Google Maps Api 3,有人能告诉我为什么这不起作用吗 jeMarkers是一组谷歌地图标记 function toggleBounce() { var bcounter = 0; $(jeMarkers).each(function () { setTimeout(function () { if (this.getAnimation() != null) { this.setAnimation(null);

有人能告诉我为什么这不起作用吗

jeMarkers是一组谷歌地图标记

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

您必须在函数中缓存
对象,因为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++;
    });
}
函数toggleBounce(){
var b计数器=0;
$(jeMarkers)。每个(函数(){

var that=this;//在
$中尝试设置超时。每个
而不是
$(“元素”)。每个()都
。这称为闭包(如:“JavaScript在
var that
周围创建闭包”),这是JavaScript最有用的功能之一。更多关于闭包的信息:就是这样!我确信我在所有尝试中都做了类似的事情,但显然我没有做对。非常感谢!!