jQuery 每次循环 returns 数据两次

jQuery each loop returns data twice

请玩下面的fiddle。一只虫子如其所愿 - 转动它的 "head" 并朝正确的方向爬行。但是几个错误(从两个开始)摧毁了这一切。 Jquery "each" returns 坐标两次 因此生成的两个错误不是两组坐标,而是四个。

$(document).ready(function () {


    function bug() {
        $('.bug').each(function () {
            //var bugs = $('.bug').length;

            var h = $(window).height() / 2;
            var w = $(window).width() / 2;
            var nh = Math.floor(Math.random() * h);
            var nw = Math.floor(Math.random() * w);



            //$this = $(this);
            //var newCoordinates = makeNewPosition();
            var p = $(this).offset();
            var OldY = p.top;
            var NewY = nh;

            var OldX = p.left;
            var NewX = nw;

            var y = OldY - NewY;
            var x = OldX - NewX;
            angle = Math.atan2(y, x);
            angle *= 180 / Math.PI
            angle = Math.ceil(angle);

            console.log(p);

            $(this).delay(1000).rotate({
                animateTo: angle
            });



            $(this).animate({
                top: nh,
                left: nw
            }, 5000, "linear", function () {
                bug();
            });

        });
    };

    bug();
});

http://jsfiddle.net/p400uhy2/
http://jsfiddle.net/p400uhy2/4/

问题是您有 .each() 调用其中包含 .each() 的函数...所以每个错误都有 bug() 回调。您只需将 bug() 调用移到 .each(){} 之外。参见 fiddle:http://jsfiddle.net/p400uhy2/2/

@Noah B 所述,问题是每个 "bug" 都在为所有 "bugs".

我会为每个元素创建 bug() 函数,这样每个 "bug" 都可以单独设置。

编辑@Roko C. Buljan 评论)

function bug() {
    // ... your code ...

    // calculate animation time, so that each of bugs runs same fast in long and short distance:
    var top_diff = Math.abs(OldY - nh),
        left_diff = Math.abs(OldX - nw),
        speed = Math.floor(Math.sqrt((top_diff * top_diff) + (left_diff * left_diff))) * 15;

    $(this).animate({
        top: nh,
        left: nw
    }, speed, "linear", function () {
        // rerun bug() function only for that single element:
        bug.call(this);
    });
};

$('.bug').each(bug);

DEMO