为什么我的foreach感到困惑?

时间:2013-07-11 19:39:21

标签: jquery

我连续更新三个输入,通过单击按钮顺序更新它们,并在完成更新后对每个输入做一个很酷的颜色变化(发光)效果:

你应该看到这样的东西,其中t =时间(我觉得自己像个科学家)

    [30.20]  [20.32]  [34.33]  [Update] <--- Clicked this
t=1 Glow
t=2          Glows     
t=3                   Glows

但有时颜色效果会出现故障:

    [30.20]  [20.32]  [34.33]  [Update] <--- Clicked this
t=1 Glow
t=2                   Glows
t=3          Glows     

这是我的剧本:

仅供参考:我测试过并发现无序问题始于.each

在页面上,它们是一个接一个。

function UpdatePrice(TheButton, Type) {
    $(TheButton).parent().parent().find("input").each(function (index, element) {

        $.ajax({
            cache: false,
            data: { ByContractID: $(element).parent().attr("id"), Cost: $(element).val(), ItemType: Type },
            type: "Post",
            url: '@Url.Action("UpdateCost")'
        }).success(function () {

            $(element).next().html(($(TheButton).parent().parent().children("td").eq(0).html() * $(element).val()).toFixed(2));
            $(element).val(parseFloat($(element).val()).toFixed(2));
            var old = $(element).css('background-color');
            $(element).animate({ "background-color": "#D2F0C9" }, "fast", function () { $(element).animate({ "background-color": old }, "fast") });


        });


    });

    return false;
}

你们都在想什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在执行ajax请求,并且每个请求可能需要不同的时间...因为ajax是异步的,所以它们都在同一时间执行,其中一个首先返回第一个输出,等等。

答案 1 :(得分:2)

尝试在我的回答here中使用Queue,然后您可以执行以下操作:

function UpdatePrice(TheButton, Type) {
    var q = new Queue;
    $(TheButton).parent().parent().find("input").each(function (index, element) {
        //add to the Queue
        q.add(function(){
            $.ajax({
                cache: false,
                data: { ByContractID: $(element).parent().attr("id"), Cost: $(element).val(), ItemType: Type },
                type: "Post",
                url: '@Url.Action("UpdateCost")'
            }).success(function () {

                $(element).next().html(($(TheButton).parent().parent().children("td").eq(0).html() *     $(element).val()).toFixed(2));
                $(element).val(parseFloat($(element).val()).toFixed(2));
                var old = $(element).css('background-color');
                $(element).animate({ "background-color": "#D2F0C9" }, "fast", function () {     $(element).animate({ "background-color": old }, "fast") });

                q.next(); //run next function

            });

            return false; 
            // ^^ insures that the queue does not continue when the function is finished.
        });

    });

    return false;
}

你必须这样做的原因是因为Ajax是异步的,所以为了按顺序运行它们,你必须在之前运行新的ajax调用 p>